<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Datareport extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct()
	 {
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Datareport_m','m');
		$this->pageSize =$this->config->item('pagenum');
	 }

	public function index()
	{
		$this -> tpl -> display("datareport/welcome.tpl");
	}
	public function newproductProsList()
	{
		$sku = trim($this->input->get('sku'));
		
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			//管理员和财务进来能看到所有人的
			
		}else{
			//其他人只能看到自己
			$where=" AND A.createName ='".$_COOKIE["username"]."'";	
		}


		$sql = "SELECT * FROM db_product_develop A left join db_goods_parent B on A.sku = B.p_parent_sku AND B.p_parent_id >0 WHERE 1 AND status = 6 AND A.sku ='".$sku."' $where AND sku in(SELECT p_parent_sku FROM db_goods_parent WHERE p_parent_id >0) ";
		$rs = $this->db->get_one($sql);
		if(!$rs)
		{
			die('Error');
		}
		
		
			$onefishTime =  date("Y-m-d",$rs['overtime']);//提成开始计算时间为完成时间
			$TwofishTime   =  date("Y-m-d",($rs['overtime']+90*86400));//提成结束时间为完成时间之后的90天
			//关于结算时间，如果上次结算时间没有，结算时间为上架时间
			if($rs['cutoff_time'] == '0000-00-00' || $rs['cutoff_time'] == '')
			{
				$time1 =$onefishTime;
			}else{
				$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
			}

		$money = $this->m->getexternalBuySell($rs['sku'],$time1,$TwofishTime,$onefishTime,$TwofishTime,1,$rs['types']);

		$this->tpl->assign("qsorder",$money['dates']);
		$this->tpl->assign("allprofits",$money['allprofits']);
		$this->tpl->assign("alllastMoney",$money['alllastMoney']);
		$this->tpl->assign("detail",$rs);
		$this->tpl->assign("time1",$time1);
		$this->tpl->assign("finishTime",date("Y-m-d",$rs['overtime']));
		$this->tpl->assign("onefishTime",$TwofishTime);
		$this->tpl->assign("TwofishTime",date("Y-m-d",$TwofishTime));
		$this -> tpl -> display("datareport/newproductProsList.tpl");
	}
	/********************正向开发商品提成报表***************
	上架时间三个月以内所有已发货订单的10%提成
	**************************************************/
	public function newproductPro($all=0)
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		//$where=" and overtime >= '".strtotime('2018-05-01')."' and status = 6";
		$where=" and  status = 6 and overtime >0 ";
		$orderby = "order by id DESC";
		$field=' * ';
		
		//搜索条件
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			//管理员和财务进来能看到所有人的
			$developer= trim(urldecode($this->input->get_post('developer')));
			if($developer)
			{
				$where.=" AND createName ='".$developer."'";	//这里使用维护者，后期有可能开发人员和维护人员不是同一个，以维护人员为准
				$this->tpl->assign("developer", $developer);
			}
		}elseif($_COOKIE["classid"] ==12 || $_COOKIE["classid"] ==13 || $_COOKIE["classid"] ==16){
			
			if($_COOKIE["classid"] ==12)	//工厂1人员
			{
				$where.=" AND supplier = 1";
			}
			if($_COOKIE["classid"] ==13)	//工厂2人员
			{
				$where.=" AND supplier = 2";
			}
			if($_COOKIE["classid"] ==16)	//工厂3人员
			{
				$where.=" AND supplier = 7";
			}

		}else{
			//其他人只能看到自己
			$where.=" AND createName ='".$_COOKIE["username"]."'";	
		}
		$factory_id= trim(urldecode($this->input->get_post('factory_id')));
		if($factory_id)
		{
			$where.=" AND supplier ='".$factory_id."'";
			$this->tpl->assign("factory_id", $factory_id);
		}

		$other= trim($this->input->get_post('other'));
		if($other)
		{
			$where.=" AND (sku ='".$other."') or name ='".$other."'";
			$this->tpl->assign("other", $other);
		}

		$starttime= trim($this->input->get_post('starttime'));
		if($starttime)
		{
			$where.=" AND overtime >='".strtotime($starttime)."'";
			$this->tpl->assign("starttime", $starttime);
		}
		$endtime= trim($this->input->get_post('endtime'));
		if($endtime)
		{
			$where.=" AND overtime <='".strtotime($endtime)."'";
			$this->tpl->assign("endtime", $endtime);
		}
		$overtime= trim($this->input->get_post('overtime'));
		if($overtime)
		{
			$where.=" AND  overtime+90*86400  >= '".strtotime($overtime)."'";
			$this->tpl->assign("overtime", $overtime);
		}
		$over2= trim($this->input->get_post('over2'));
		if($over2)
		{
			$where.=" AND  overtime+90*86400 <= '".strtotime($over2)."'";
			$this->tpl->assign("over2", $over2);
		}
		if($all==1)
		{
			$if_csv =1;
			$listcount = 0;
		}
		if(trim($this->input->get_post('flagtype'))==1){
		
			$if_csv =1;
		}

		$list = $this->fun->getalllist('db_product_develop ',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		foreach($list["list"] as $key=>$rs)
		{
			$startdate =  date("Y-m-d",$rs['overtime']);//提成开始计算时间为完成时间
			$enddate   =  date("Y-m-d",($rs['overtime']+90*86400));//提成结束时间为完成时间之后的90天

			$list['list'][$key]["startdate"] = $startdate;
			$list['list'][$key]["enddate"] = $enddate;
			//关于结算时间，如果上次结算时间没有，结算时间为上架时间
			if($rs['cutoff_time'] == '0000-00-00' || $rs['cutoff_time'] == '')
			{
				$time1 =$startdate;
			}else{
				$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
			}
			//从开始到一年后的订单,如果时间在90天内，10%毛利
			$money = $this->m->getexternalBuySell($rs['sku'],$time1,$enddate,$enddate,0,0,$rs['types']);
			$list['list'][$key]["money"] = $money;
			$listcount = $listcount+$money['alllastMoney'];
		}
		
		//导出excel
		if(trim($this->input->get_post('flagtype'))==1){
			require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
			$objExcel = new PHPExcel();

			$objExcel->setActiveSheetIndex(0);
			$objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
			$objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(36);
			$objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
			$objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
			$objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);

			//设置标题
			$objExcel->setActiveSheetIndex(0)->setCellValue('A1','商品编号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('B1','商品名称');
			$objExcel->setActiveSheetIndex(0)->setCellValue('C1','上架时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('D1','提成结束时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('E1','开发者');
			$objExcel->setActiveSheetIndex(0)->setCellValue('F1','上次结算时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('G1','未结金额');
			$objExcel->setActiveSheetIndex(0)->setCellValue('H1','已结金额');

			foreach($list["list"] as $k=>$v){
				$count = $k+2;
				$objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['sku']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['name']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['startdate']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['enddate']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['createName']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['cutoff_time']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$v['money']['alllastMoney']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$v['cutoff_money']);
			}
			$excel_name = date("YmdHis");
			header("Content-type:application/vnd.ms-excel;charset=gb2312");
			header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
			header('Cache-Control: max-age=0');
			$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
			$objWriter->save('php://output');
			exit;
		}


		if($all==1)
		{
			echo json_encode($listcount);
			die;
		}
	
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("userid",$_COOKIE["userid"]);
		
	
		$factorylist=$this->db->get('db_factory')->result_array();
        $this->tpl->assign('factorylist',$factorylist);

		$userlist = $this->fun->getdatabaseslist('db_product_develop'," AND createName is NOT NULL AND status = 6",'DISTINCT(createName)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['createName'];
		}
        $this->tpl->assign("userlist", $yuanl);

		$this -> tpl -> display("datareport/newproductPro.tpl");
	}

	/********************订单负利润报表***************
	当前未发货的订单，负利润报表
	**************************************************/
	public function ordernegative()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$where=" AND order_status in(2,3) AND (order_source='正常订单' or order_source='手工创建' or order_source='合并订单' ) and shopname !='赞助' AND dates >='".date("Y-m-d",time()-86400*90)."'";
		$factory = $this->input->get('factory');
		if($factory)
		{
			$where.=" AND B.goods_id in( SELECT goods_id FROM db_goods WHERE g_supplier = $factory )";
			$this->tpl->assign("made_factory",$factory);
		}
		$sku = trim($this->input->get('sku'));
		if($sku)
		{
			$where.=" AND B.goods_sn like '%".$sku."%'";
			$this->tpl->assign("sku",$sku);
		}
		
		//如果进来的是管理员，能看到所有人的，
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			$ch = trim($this->input->get('ch'));
			if($ch)
			{
				$where.=" AND B.goods_id in( SELECT goods_id FROM db_goods WHERE g_checkman = '".$ch."' )";
				$this->tpl->assign("ch",$ch);
			}
		}else{
			//其他人只能看到自己
			$where.=" AND (B.goods_id in( SELECT goods_id FROM db_goods WHERE g_checkman = '".$_COOKIE['username']."' ) or A.shopoper = '".$_COOKIE['username']."')  ";
			//店铺负责人
		}
		//如果是进来的开发人员，只能看到属于自己的

		
		$orderby = " GROUP BY order_id having ch<0 order by A.order_id DESC";
		$field=' GROUP_CONCAT(B.goods_sn) as goods_sn,A.order_id,dates,shipping_realfee,shipping_expectfee,A.goods_amount,shipping_fee,platform_fee,pay_fee,order_sn,sum(costprice*goods_number) as costprice_total ,
		(A.goods_amount+shipping_fee-shipping_expectfee - platform_fee-pay_fee-sum(costprice*goods_number))  as ch ';
		$list = $this->fun->getalllist('db_order_list A LEFT JOIN db_order_sell B on A.order_id = B.order_id',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("userid",$_COOKIE["userid"]);
		
	
		$factorylist=$this->db->get('db_factory')->result_array();
        $this->tpl->assign('factorylist',$factorylist);
		$this -> tpl -> display("datareport/ordernegative.tpl");
	}
	


	/*******************商品清仓报表*************/
	public function stockclear($all=0)
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$where="";
		$field='*';
		$orderby = " order by id ASC";
		if($this->input->get_post('shopname'))
		{
			 $shopname = trim($this->input->get_post('shopname'));
			  $shopnames =substr($shopname,0,-1);
			  $shopnames=explode(',',$shopnames);
    		  $whereshop = implode("','",$shopnames);
			  $rsdb = $this->fun->getdatabasesdetail("d_shop"," AND name in('".$whereshop."')","GROUP_CONCAT(id) as id");
			  $shopid = $rsdb['id'];
			  $where.=" AND shopid in($shopid)";
			 $this->tpl->assign("shopname", $shopname);
		}
		if($this->input->get_post('other'))
		{
			 $where.=" AND sku like  '%".trim($this->input->get_post('other'))."%'";
			 $this->tpl->assign("other", trim($this->input->get_post('other')));
		}
		if($this->input->get_post('int_value'))
		{
			 $where.=" AND interest >='".trim($this->input->get_post('int_value'))."'";
			 $this->tpl->assign("int_value", trim($this->input->get_post('int_value')));
		}
		if($all==1)
		{
			$if_csv =1;
			$listcount = $allprofits=$allmoneys=$nums=0;
		}

		$list = $this->fun->getalllist('db_goods_clear_detail',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		foreach($list["list"] as $key=>$rs)
		{
			 $list["list"][$key]["starttime"]=date("Y-m-d",$rs['instime']);
			 $list["list"][$key]["price"]= round(($rs['discount_price'] / $rs["discount"]) * 100 ,2);	//原始价格

			 $rsdb = $this->fun->getdatabasesdetail("db_goods_stock"," AND storage_id in(1,2) AND goods_id ='".$rs['goods_id']."'"," SUM(stock) as stock ");//当前库存
			 $list["list"][$key]["nowstock"]= $rsdb['stock']?$rsdb['stock']:0;
			 //报表
			
				if($rs['cutoff_time'] == '0000-00-00')
				{
					$time1 = date("Y-m-d",$rs['instime']);
				}else{
					$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
				}
				
				$money = $this->m->getstockcleardataList($rs['goods_id'],$time1,0);
				$list['list'][$key]["money"] = $money;
				$listcount = $listcount+$money['alllastMoney'];
				$allprofits = $allprofits+$money['allprofits'];
				$allshourumoney = $allshourumoney+$money['allshourumoney'];
				$allmoneys =$allmoneys  + ($rs["confirmstock"] * $rs["discount_price"]);
				$nums = $nums+$rs["confirmstock"];
		}
		if($all)
		{
			echo json_encode(array("listcount"=>$listcount,"allprofits"=>$allprofits,"allmoneys"=>$allmoneys,"nums"=>$nums,"allshourumoney"=>$allshourumoney));
			die;
		}


		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("userid",$_COOKIE["userid"]);
		
	
		$this->tpl->assign("allprofits",$allprofits);
		$this -> tpl -> display("datareport/stockclear.tpl");
	}
	public function stockclearlist()
	{
		$goods_id = intval($this->input->get('goods_id'));
		
		$sql = "SELECT * FROM db_goods_clear_detail where  goods_id = '".$goods_id."'";
		$rs = $this->db->get_one($sql);

		 $rsdb = $this->fun->getdatabasesdetail("db_goods_stock"," AND storage_id in(1,2) AND goods_id ='".$goods_id."'"," SUM(stock) as stock ");//当前库存
		 $rs["nowstock"]= $rsdb['stock']?$rsdb['stock']:0;
		if(!$rs)
		{
			die('Error');
		}
		if($rs['cutoff_time'] == '0000-00-00')
		{
			$time1 =  date("Y-m-d",$rs['instime']);
		}else{
			$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
		}
		$money = $this->m->getstockcleardataList($goods_id,$time1,1);
		
		$this->tpl->assign("qsorder",$money['dates']);
		$this->tpl->assign("allprofits",$money['allprofits']);
		$this->tpl->assign("alllastMoney",$money['alllastMoney']);
		$this->tpl->assign("detail",$rs);
		$this->tpl->assign("time1",date("Y-m-d",strtotime($time1)));
		$this->tpl->assign("finishTime",date("Y-m-d",strtotime($rs["finishTime"])));
		$this->tpl->assign("onefishTime",date("Y-m-d",$onefishTime));
		$this->tpl->assign("TwofishTime",date("Y-m-d",$TwofishTime));
		$this -> tpl -> display("datareport/stockclearlist.tpl");
	}
	/*********商品库息报表**********************/
	public function interest()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$where=" AND isfba = 1";
		$field='*';
		$orderby = " order by interest DESC,shopid ASC";
		if($this->input->get_post('shopname'))
		{
			 $shopname = trim($this->input->get_post('shopname'));
			  $shopnames =substr($shopname,0,-1);
			  $shopnames=explode(',',$shopnames);
    		  $whereshop = implode("','",$shopnames);
			  $rsdb = $this->fun->getdatabasesdetail("d_shop"," AND name in('".$whereshop."')","GROUP_CONCAT(id) as id");
			  $shopid = $rsdb['id'];
			  $where.=" AND shopid in($shopid)";
			 $this->tpl->assign("shopname", $shopname);
		}
		if($this->input->get_post('other'))
		{
			 $where.=" AND goods_sku like  '%".trim($this->input->get_post('other'))."%'";
			 $this->tpl->assign("other", trim($this->input->get_post('other')));
		}
		if($this->input->get_post('int_value'))
		{
			 $where.=" AND interest >='".trim($this->input->get_post('int_value'))."'";
			 $this->tpl->assign("int_value", trim($this->input->get_post('int_value')));
		}

		$list = $this->fun->getalllist('db_goods_stock_interest',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		foreach($list["list"] as $key=>$rs)
		{
			 $list["list"][$key]["starttime"]=date("Y-m-d",$rs['starttime']);
			 $rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_id ='".$rs['goods_id']."'","goods_name");
			 $rsdbshop = $this->fun->getdatabasesdetail("d_shop"," AND id ='".$rs['shopid']."'","name");
			
			  $list["list"][$key]["goods_name"]=$rsdb['goods_name'];
			  $list["list"][$key]["shopname"]=$rsdbshop['name'];
			  if($rs["settlement"]==0)
				{
				$list["list"][$key]["settlement"]='未结算';
			  }else{
			  $list["list"][$key]["settlement"]=date("Y-m-d",$rs["settlement"]);
			  }
	
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("userid",$_COOKIE["userid"]);
		

		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop'," AND openflag= 1 AND platfromname='Amazon'",'id,name',' order by name asc'));			//查所有店铺
		$this -> tpl -> display("datareport/interest.tpl");
	}


	/***********查询一下当前停售商品一个月和万圣节销量************
	** 
	*************************************************/
	public function  haltgoodssales()
	{
		$newlist = array();
		$starttime = trim($this->input->get('starttime'));
		$starttime = $starttime?$starttime:'2017-09-15';
		$endtime = trim($this->input->get('endtime'));
		$endtime = $endtime?$endtime:'2017-10-30';
		$salenum = $this->input->get('salenum')?$this->input->get('salenum'):10;//万圣节销量
		$num = $this->input->get('num')?$this->input->get('num'):5;//平时销量
		$month = $this->input->get('month')?$this->input->get('month'):1;//平时销量
		
		$monthstart = date("Y-m-d");
		$monthend  =date('Y-m-01' ,strtotime("-{$month} month"));
		$status = trim($this->input->get('status'));
		$status = $status?$status:'4';
		if($status ==6)
		{
			$list = $this->db->get_where("db_goods","g_sale_status=6 or g_sale_status =7")->result_array();	//所有停售的商品
		}else{
			$list = $this->db->get_where("db_goods","g_sale_status={$status}")->result_array();	//所有停售的商品
		}
		
		foreach($list as $key=>$rs)
		{
			//万圣节出单10个
			$istop = 0;
			if($istop ==0)
			{
				$res = $this->fun->getdatabasesdetail("db_order_sell A LEFT JOIN db_order_list B on A.order_id =B.order_id "," AND A.goods_id = '".$rs['goods_id']."' AND B.order_status=5 AND B.dates >='".$monthend."' AND B.dates <='".$monthstart."'","sum(goods_number) as salenum ");
				
				if($res['salenum'] >= intval($num))
				{
					$istop = 1;
					$rs["iswang"] = 2;
					$rs["salenum"] = $res['salenum'];
				}
			}
			if($istop ==0)
			{
				$res = $this->fun->getdatabasesdetail("db_order_sell A LEFT JOIN db_order_list B on A.order_id =B.order_id "," AND A.goods_id = '".$rs['goods_id']."' AND B.order_status=5 AND B.dates >='".$starttime."' AND B.dates <='".$endtime."'","sum(goods_number) as salenum ");
				if($res['salenum'] >= intval($salenum))
				{
					$istop = 1;
					$rs["iswang"] = 1;
					$rs["salenum"] = $res['salenum'];
				}
			}

			

			if($istop==1)
			{
				$newlist[] = $rs;
			}


		}
		$this->tpl->assign("list",$newlist);
		$this->tpl->assign("starttime",$starttime);
		$this->tpl->assign("endtime",$endtime);
		$this->tpl->assign("salenum",$salenum);
		$this->tpl->assign("num",$num);
		$this->tpl->assign("status",$status);
		$this->tpl->assign("month",$month);
		$this -> tpl -> display("datareport/haltgoodssales.tpl");
	}


	/***********审核商品停售列表************
	*************************************************/
	public function haltsales_check()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$where=" AND types = 1";
		$field='*';
		$orderby = " group by parent_id order by uptime DESC";

		$list = $this->fun->getalllist('db_goods_clear_list A left join db_goods_parent B on A.parent_id = B.p_parent_id',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		foreach($list["list"] as $key=>$rs)
		{
			 $list["list"][$key]["g_updatetime"]=date("Y-m-d",strtotime($rs["p_updatetime"]));
			 $rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID ='".$rs['p_parent_id']."'","GROUP_CONCAT(goods_id) as goods_id");
			  $stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND  goods_id IN ($rsdb[goods_id]) and stock>0  AND B.is_show = 1"," SUM(stock) as stock");
			
			 $list["list"][$key]["stock"]=$stock['stock']?$stock['stock']:0;
			  $list["list"][$key]["uptime"]=date("Y-m-d",$rs["uptime"]);
	
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("userid",$_COOKIE["userid"]);
		

		$this->tpl->assign("factory", $this->db->get('db_factory')->result_array());
		$this -> tpl -> display("datareport/haltsales_check.tpl");
	}
	/***********自动生成需要停售的商品列表************
	** 1、列出所有暂停销售的商品
	** 2、列出所有五个月内没有销售的SKU
	*************************************************/
	public function haltsales()
	{
		$sm = $this->input->get('sm');
		
		if($sm=='0')
		{
			$endtime = "";
		}else{
			$sm=$sm?$sm:5;
			$endtime   =  date("Y-m-d",strtotime("-{$sm} month"))." 00:00:00";
			$wendtime = " AND p_updatetime <='".$endtime."'";
		}
		$this->tpl->assign("sm",$sm);
		
		$orderstatus = $this->input->get('orderstatus');
		if(!$orderstatus || $orderstatus ==8)
		{
			$wherestatus = "";
			$this->tpl->assign("orderstatus",8);
		}else{
			$wherestatus = " AND C.order_status = 5";
			$this->tpl->assign("orderstatus",$orderstatus);
		}
		$isstop = $this->input->get('isstop');
		if($isstop){
			$stopwhere=" p_sale_status = 6 OR ";
			$this->tpl->assign("isstop",1);
		}

		$dm = $this->input->get('dm');
		if($dm=='0')
		{
			$endtimes = "";
		}else{
			$dm=$dm?$dm:5;
			$endtimes   =  date("Y-m-d",strtotime("-{$dm} month"));
			$whereendtime = " and (  $stopwhere  p_parent_id not in (SELECT DISTINCT(B.goods_parentID) from db_order_sell A LEFT JOIN db_goods B on A.goods_id =B.goods_id LEFT JOIN db_order_list C on A.order_id = C.order_id where C.dates >='".$endtimes."' $wherestatus HAVING goods_parentID >0))";
		}
		$this->tpl->assign("dm",$dm);
		$istock = $this->input->get('istock');
		
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		//SELECT * from db_goods_parent where p_yz = 0 and  p_updatetime <='2017-09-10'  and p_parent_id not in(SELECT goods_id FROM `db_goods_clear_list`) and p_sale_status !=4 and (p_sale_status =6 or p_parent_id not in(SELECT DISTINCT(B.goods_parentID) from db_order_sell A left join db_goods B on A.goods_id = B.goods_id where A.order_id in (SELECT order_id from db_order_list where 1 and dates >='2017-09-10' and order_status = 5)))
		
		//$strsql = " AND p_parent_id in(SELECT DISTINCT(goods_parentID) FROM db_goods where yz = 0 and g_sale_status in(1,2,3,6))";
		
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11 || $_COOKIE["department"] ==2 || $_COOKIE["classid"] ==12  || $_COOKIE["classid"] ==13)
		{
			//管理员和财务进来能看到所有人的
			$developer= trim(urldecode($this->input->get_post('developer')));
			if($developer)
			{
				$wheredev=" AND p_checkman ='".$developer."'";	//这里使用维护者，后期有可能开发人员和维护人员不是同一个，以维护人员为准
				$this->tpl->assign("developer", $developer);
			}
		}else{
			//其他人只能看到自己
			$wheredev=" AND p_checkman ='".$_COOKIE["username"]."'";	
		}

		$where=" $wendtime $wheredev and p_yz=0 $strsql and p_parent_id not in(SELECT parent_id FROM `db_goods_clear_list`  ) and p_sale_status !=4   $whereendtime  ";
		if($istock){
			$where.=" AND p_parent_id in(SELECT DISTINCT(B.goods_parentID)  FROM db_goods_stock A LEFT JOIN db_goods B on A.goods_id = B.goods_id WHERE stock>0 AND storage_id !=8 )";
			$this->tpl->assign("istock",$istock);
		}
		$factory_id = $this->input->get_post('supplier');
		if($_COOKIE["classid"] ==12)	//工厂1人员
		{
			 $factory_id=1;
		}
		if($_COOKIE["classid"] ==13)	//工厂2人员
		{
			$factory_id=2;
		}
		if($_COOKIE["classid"] ==16)	//工厂3人员
		{
			$factory_id=7;
		}
		if ($factory_id) {
            $where .= " AND p_supplier='" . trim($factory_id) . "'";
			$this->tpl->assign("supplier", $factory_id);
        }
		 if ($this->input->get_post('bigclassID')) {
            $where .= " AND p_bigclassid='" . trim($this->input->get_post('bigclassID')) . "'";
            $this->tpl->assign("bigclassID", trim($this->input->get_post('bigclassID')));
        }
        if ($this->input->get_post('secondclassID')) {
            $where .= " AND p_secondclassid='" . trim($this->input->get_post('secondclassID')) . "'";
            $this->tpl->assign("secondclassID", trim($this->input->get_post('secondclassID')));
        }
		
		 if ($this->input->get_post('other')) {
            $other = trim($this->input->get_post('other'));
			$iskey = trim($this->input->get_post('iskey'));
			if($iskey==1) $where .= " AND ( p_parent_sku like '%" . $other . "%' or  p_parent_name like '%" . $other . "%')";
			if($iskey==2) $where .= " AND ( p_parent_sku  NOT like '%" . $other . "%' or  p_parent_name NOT like '%" . $other . "%')";
			$this->tpl->assign("other",$other);
			$this->tpl->assign("iskey",$iskey);
		 }
		$field='*';
		$orderby = " order by p_parent_id ASC";
		$list = $this->fun->getalllist('db_goods_parent',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		//echo $this->db->last_query();
		foreach($list["list"] as $key=>$rs)
		{
			 $list["list"][$key]["goods_sku"]=strtoupper($rs['goods_sku']);
			 $list["list"][$key]["g_updatetime"]=date("Y-m-d",strtotime($rs["p_updatetime"]));
			 $rsdb = $this->fun->getdatabasesdetail("db_goods"," AND goods_parentID ='".$rs['p_parent_id']."'","GROUP_CONCAT(goods_id) as goods_id");
			 $stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND  goods_id IN ($rsdb[goods_id]) and stock>0  AND B.is_show = 1"," SUM(stock) as stock");
			
			 $list["list"][$key]["stock"]=$stock['stock']?$stock['stock']:0;
		}

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("userid",$_COOKIE["userid"]);
		$categorylist = $this->db->get_where('db_goods_category', 'sort_id=0')->result_array();
        $this->tpl->assign("categorylist", $categorylist);//分类
		
		$userlist = $this->fun->getdatabaseslist('db_external_buy'," AND protector is NOT NULL AND del_flag = 0",'DISTINCT(protector)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['protector'];
		}
        $this->tpl->assign("userlist", $yuanl);
		$this->tpl->assign("factory", $this->db->get('db_factory')->result_array());
		$this -> tpl -> display("datareport/haltsales.tpl");
	}

	/***********销售平台************
	** 1、列出商品的销售平台，销售数量
	*************************************************/
	public function saleplatform()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		$where=" AND goods_parent_sku !='RUSH SERVICE'";

		$status = trim($this->input->get('status'));
		if($status)
		{
			if($status==2)
			{
				$statusst = 0;
			}else{
				$statusst = 1;
			}
			$where.=" and goods_parentID in(SELECT parent_goods_id FROM db_goods_recommend WHERE is_stop=0 and status = $statusst)";
			$this->tpl->assign("status", $status);
		}

		$where.=" and goods_parentID not in(SELECT parent_goods_id FROM db_goods_recommend WHERE is_stop=1)";
		
		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$where.=" AND g_createID in ($ext_userID)";
		
		}else{
			$notext_userID = $_COOKIE['notext_userid'];
			if($notext_userID){
				$where.=" AND g_createID not in ($notext_userID)";
			}
		}

		$saletype = $this->input->get('saletype');
		if($saletype)
		{
			if($saletype==1)$salenum = 'saleNum';
			if($saletype==2)$salenum = 'sales1';
			if($saletype==3)$salenum = 'sales2';
			if($saletype==4)$salenum = 'sales3';
			
			$this->tpl->assign("saletype", $saletype);
		}else{
			$salenum = 'saleNum';
			$this->tpl->assign("saletype", 1);
		}

		$nums = intval($this->input->get('nums'));
		if($nums)
		{
			$this->tpl->assign("nums", $nums);
		}else{
			$nums =10;
			$this->tpl->assign("nums", 10);
		}
		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND ( goods_sku like '%".$other."%' or  goods_name like '%".$other."%')";
			$this->tpl->assign("other", $other);
		}
		
		
		$list = $this->m->saleplatform_m($where,$salenum,$nums,0,$nowpage);
		
		 //推荐接收者
        $receivers_config = trim($this->config->item('externalbuyreceivers'));
        $arr_receiver_config = explode("|",$receivers_config);
        $str_receiver = "";
        foreach($arr_receiver_config as $k=>$v){
            $str_receiver.= "'".trim($v)."'".",";
        }
        $str_receiver = trim($str_receiver,",");
        $receiverlist = $this->db->get_where('d_user'," type=1  AND name in ($str_receiver) ")->result_array();
        $this->tpl->assign("receiverlist", $receiverlist);
		$arr_receiver = array();
        foreach($receiverlist as $kk=>$vv){
            $arr_receiver[$vv['id']] = $vv['name'];
        }
        $this->tpl->assign("arr_receiver", $arr_receiver);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("classid",$_COOKIE["classid"]);
		$this -> tpl -> display("datareport/saleplatform.tpl");
	}

	/***********外采产品开发人员，商品报表************
	** 外采购商品报表
	*************************************************/
	public function externalBuy($all=0)
	{
		
		
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		$where = " AND status = 99 AND del_flag = 0";
		
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			//管理员和财务进来能看到所有人的
			$developer= trim(urldecode($this->input->get_post('developer')));
			
			if($developer)
			{
				$where.=" AND protector ='".$developer."'";	//这里使用维护者，后期有可能开发人员和维护人员不是同一个，以维护人员为准
				$this->tpl->assign("developer", $developer);
			}
		}else{
			//其他人只能看到自己
			$where.=" AND protector ='".$_COOKIE["username"]."'";	
		}

		$other = trim($this->input->get_post('other'));
		if($other)
		{
			$where.=" AND A.sku like '%".$other."%'";
			$this->tpl->assign("other", $other);
		}

		
		$starttime=trim($this->input->get_post('starttime'));
		if($starttime)
		{
			$where.=" AND finishTime >='".$starttime."'";
			$this->tpl->assign("starttime", $starttime);
		}
		$endtime= trim($this->input->get_post('endtime'));
		if($starttime)
		{
			$where.=" AND finishTime <='".$endtime."'";
			$this->tpl->assign("endtime", $endtime);
		}
		
	
		
		$where.=" AND sku in(SELECT p_parent_sku FROM db_goods_parent WHERE p_parent_id >0)";
		if($all==1)
		{
			$if_csv =1;
			$listcount = 0;
		}
		$field='B.p_parent_name,sku,finishTime,protector,cutoff_time,cutoff_money,types';
		$list = $this->fun->getalllist('db_external_buy A left join db_goods_parent B on A.sku = B.p_parent_sku AND B.p_parent_id >0',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		//echo $this->db->last_query();
		//die;
		
		foreach($list["list"] as $key=>$rs)
		{
			$onefishTime = strtotime($rs["finishTime"])+90*86400;
			$TwofishTime = strtotime($rs["finishTime"])+365*86400;
			$list['list'][$key]["onefinishTime"] = date("Y-m-d H:i:s",$onefishTime);
			$list['list'][$key]["TwofinishTime"] = date("Y-m-d H:i:s",$TwofishTime);
			
			//关于结算时间，如果上次结算时间没有，结算时间为上架时间
			if($rs['cutoff_time'] == '0000-00-00')
			{
				$time1 = $rs["finishTime"];
			}else{
				$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
			}
			
			//从开始到一年后的订单,如果时间在90天内，10%毛利，90天外1%毛利
			$money = $this->m->getexternalBuySell($rs['sku'],$time1,date("Y-m-d H:i:s",$TwofishTime),$onefishTime,$TwofishTime,0,$rs['types']);
			$list['list'][$key]["money"] = $money;

			$listcount = $listcount+$money['alllastMoney'];
		}

		if($all)
		{
			echo json_encode($listcount);
			die;
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$userlist = $this->fun->getdatabaseslist('db_external_buy'," AND protector is NOT NULL AND del_flag = 0",'DISTINCT(protector)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['protector'];
		}
        $this->tpl->assign("userlist", $yuanl);
		$this -> tpl -> display("datareport/externalBuy.tpl");
	}
	/*********正向开发商品报表*************/
	public function newproduct()
	{
		ini_set('max_execution_time', '0');
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "")
			$nowpage = 1;
		$where = " AND a.status = 6 ";

		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11 || $_COOKIE["department"] ==2)
		{
			//管理员和财务进来能看到所有人的
			$developer= trim(urldecode($this->input->get_post('developer')));
			if($developer)
			{
				$where.=" AND a.createName ='".$developer."'";
				$this->tpl->assign("developer", $developer);
			}
		}else{
			//其他人只能看到自己
			$where.=" AND a.createName ='".$_COOKIE["username"]."'";
		}

		$other = trim($this->input->get_post('other'));
		if($other)
		{
			$where.=" AND a.sku like '%".$other."%'";
			$this->tpl->assign("other", $other);
		}
		$starttime=trim($this->input->get_post('starttime'));
		if($starttime)
		{
			$where.=" AND a.enddate >='".$starttime."'";
			$this->tpl->assign("starttime", $starttime);
		}
		$endtime= trim($this->input->get_post('endtime'));
		if($starttime)
		{
			$where.=" AND a.enddate <='".$endtime."'";
			$this->tpl->assign("endtime", $endtime);
		}

		$jiesuan = trim($this->input->get_post("jiesuan"));
		if($jiesuan){
			if($jiesuan==1){
				$where .= " AND a.cutoff_time IS NOT NULL "; //已结算
			}
			if($jiesuan==2){
				$where .= " AND a.cutoff_time IS NULL "; //未结算
			}
			$this->tpl->assign("jiesuan",$jiesuan);
		}else{
			$where .= " AND a.cutoff_time IS NULL "; //未结算
		}
		$where.= " AND startdate IS NOT NULL AND overtime <= 1525017600";	//截取到4月30号，5月新上的SKU，换另外的计算方式
		$sql_totalmoney = "SELECT SUM(cutoff_money) as total_money FROM db_product_develop a WHERE 1 ".$where;
		$rs_totalmoney  = $this->db->query($sql_totalmoney)->row_array();
		$this->tpl->assign("total_money",$rs_totalmoney['total_money']);
		//导出excel
		if(trim($this->input->get_post('flagtype'))==1){
			require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
			$objExcel = new PHPExcel();
			$where ="SELECT * FROM db_product_develop a where 1 ".$where;
			$result = $this->db->query($where)->result_array();

			$objExcel->setActiveSheetIndex(0);
			$objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
			$objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(36);
			$objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
			$objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
			$objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);

			//设置标题
			$objExcel->setActiveSheetIndex(0)->setCellValue('A1','商品编号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('B1','商品名称');
			$objExcel->setActiveSheetIndex(0)->setCellValue('C1','上架时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('D1','结束时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('E1','30天销量(连续)');
			$objExcel->setActiveSheetIndex(0)->setCellValue('F1','90天销量');
			$objExcel->setActiveSheetIndex(0)->setCellValue('G1','开发者');
			$objExcel->setActiveSheetIndex(0)->setCellValue('H1','结算时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('I1','结算金额');

			foreach($result as $k=>$v){
				$count = $k+2;
				$objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['sku']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['name']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['startdate']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['enddate']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['nums_30day']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['nums_90day']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$v['createName']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$v['cutoff_time']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('I'.$count,$v['cutoff_money']);
			}
			$excel_name = date("YmdHis");
			header("Content-type:application/vnd.ms-excel;charset=gb2312");
			header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
			header('Cache-Control: max-age=0');
			$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
			$objWriter->save('php://output');
			exit;
		}


		//显示数据
		$list = $this->fun->getalllist('db_product_develop a',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field="*");
		//echo $this->db->last_query();exit;
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		//操作者
		$userlist = $this->fun->getdatabaseslist('db_product_develop'," AND createName is NOT NULL ",'DISTINCT(createName)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['createName'];
		}
		$this->tpl->assign("userlist", $yuanl);
		$this ->tpl->display("datareport/newproduct.tpl");
	}
	public function externalBuyList()
	{
		$sku = trim($this->input->get('sku'));
		
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			//管理员和财务进来能看到所有人的
			
		}else{
			//其他人只能看到自己
			$where=" AND A.protector ='".$_COOKIE["username"]."'";	
		}


		$sql = "SELECT * FROM db_external_buy A left join db_goods_parent B on A.sku = B.p_parent_sku AND B.p_parent_id >0 WHERE 1 AND status = 99 AND A.sku ='".$sku."' $where AND sku in(SELECT p_parent_sku FROM db_goods_parent WHERE p_parent_id >0) ";
		$rs = $this->db->get_one($sql);
		if(!$rs)
		{
			die('Error');
		}
		$onefishTime = strtotime($rs["finishTime"])+90*86400;
		$TwofishTime = strtotime($rs["finishTime"])+365*86400;
		if($rs['cutoff_time'] == '0000-00-00')
		{
			$time1 = $rs["finishTime"];
		}else{
			$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
		}
		$money = $this->m->getexternalBuySell($rs['sku'],$time1,date("Y-m-d H:i:s",$TwofishTime),$onefishTime,$TwofishTime,1,$rs['types']);

		$this->tpl->assign("qsorder",$money['dates']);
		$this->tpl->assign("allprofits",$money['allprofits']);
		$this->tpl->assign("alllastMoney",$money['alllastMoney']);
		$this->tpl->assign("detail",$rs);
		$this->tpl->assign("time1",date("Y-m-d",strtotime($time1)));
		$this->tpl->assign("finishTime",date("Y-m-d",strtotime($rs["finishTime"])));
		$this->tpl->assign("onefishTime",date("Y-m-d",$onefishTime));
		$this->tpl->assign("TwofishTime",date("Y-m-d",$TwofishTime));
		$this -> tpl -> display("datareport/externalBuyList.tpl");
	}
	
	//新品开发结算报表
	public function newproductList()
	{
		$sku = trim($this->input->get('sku'));
		$sql_develop = "SELECT * FROM db_product_develop WHERE sku = '{$sku}' ";
		$rs_develop  = $this->db->query($sql_develop)->row_array();
		$where = " WHERE 1 ";
		$where.= " AND b.dates>= '{$rs_develop['startdate']}' AND b.dates <= '{$rs_develop['enddate']}' ";
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			//管理员和财务进来能看到所有人的

		}else{
			//其他人只能看到自己
			//$where=" AND A.protector ='".$_COOKIE["username"]."'";
		}
		$where .= " AND a.goods_id in (SELECT goods_id FROM db_goods WHERE goods_parent_sku = '{$sku}') ";

		//亚马逊平台存在的订单
		$where_amazon = $where." GROUP BY a.ordertmpid ";
		$fields_amazon = "a.ordertmpid as order_id,b.tradeid as order_sn,b.goods_amount,b.shipping_fee,b.pay_fee";
		$fields_amazon.= ",b.platform_fee,b.shopname ";
		$sql_amazon = "SELECT {$fields_amazon} FROM db_amzordertmpsell a LEFT JOIN db_amzordertmp b ON a.ordertmpid = b.id ".$where_amazon;
		$rs_amazon  = $this->db->query($sql_amazon)->result_array();
		$this->tpl->assign("listamazon",$rs_amazon);

		$where .= " AND b.order_status in(4,5) AND b.order_source in('正常订单','手工创建','拆分订单','合并订单') ";
		$where .= " GROUP BY a.order_id ";
		$fields = "a.order_id,b.order_sn,b.order_source,b.goods_amount,b.shipping_fee,b.pay_fee,b.platform_fee,b.shopname,b.shipping_realfee,b.shipping_expectfee,b.shipping_time";
		$sql = "SELECT {$fields} FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id ".$where;
		$rs  = $this->db->query($sql)->result_array();
		$total_money = 0;
		$total_costprice = 0;
		$total_profit = 0;
		foreach($rs as $k=>$v){
			$sql_costprice = "SELECT SUM(costprice) as costprice FROM db_order_sell WHERE order_id = '{$v['order_id']}' ";
			$rs_costprice  = $this->db->query($sql_costprice)->row_array();
			$rs[$k]['costprice'] = $rs_costprice['costprice'];
			$rs[$k]['profit'] = $v['goods_amount']+$v['shipping_fee']-$rs_costprice['costprice']-$v['platform_fee']-$v['pay_fee']-$v['shipping_realfee'];
			$total_money+=$v['goods_amount'];
			$total_costprice+=$rs_costprice['costprice'];
			$total_profit+=$rs[$k]['profit'];
			if($v['shipping_time']){
				$rs[$k]['shipping_time'] = date("Y-m-d H:i:s",$v['shipping_time']);
			}else{
				$rs[$k]['shipping_time'] = "";
			}

		}
		$this->tpl->assign("total_money",$total_money);
		$this->tpl->assign("total_costprice",$total_costprice);
		$this->tpl->assign("total_profit",$total_profit);
		$this->tpl->assign("list",$rs);
		$this -> tpl -> display("datareport/newproductlist.tpl");
	}

	public function updateshopdata()
	{
		$this->load->library('Mabang');
		$this->mabang->updateshopdata();	//更新马帮里面所有的店铺到系统d_shop表
	}
	
	/*******外采购商品退款报表************/
	public function externalBuy_refund($all=0)
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		$where = " AND status = 99 AND del_flag = 0";
		
		if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
		{
			//管理员和财务进来能看到所有人的
			$developer= trim($this->input->get_post('developer'));
			if($developer)
			{
				$where.=" AND protector ='".$developer."'";	//这里使用维护者，后期有可能开发人员和维护人员不是同一个，以维护人员为准
				$this->tpl->assign("developer", $developer);
			}
		}else{
			//其他人只能看到自己
			$where.=" AND protector ='".$_COOKIE["username"]."'";	
		}

		$other = trim($this->input->get_post('other'));
		if($other)
		{
			$where.=" AND A.sku like '%".$other."%'";
			$this->tpl->assign("other", $other);
		}

		
		$starttime=trim( $this->input->get_post('starttime'));
		if($starttime)
		{
			$where.=" AND finishTime >='".$starttime."'";
			$this->tpl->assign("starttime", $starttime);
		}
		$endtime= trim($this->input->get_post('endtime'));
		if($starttime)
		{
			$where.=" AND finishTime <='".$endtime."'";
			$this->tpl->assign("endtime", $endtime);
		}
		
	
		
		$where.=" AND sku in(SELECT p_parent_sku FROM db_goods_parent WHERE p_parent_id >0)";
		$where.=" and p_parent_id in ( SELECT distinct(goods_parentID) FROM `db_goods`  where saleNum >0   group by goods_id desc)";
		if($all==1)
		{
			$if_csv =1;
			$listcount = 0;
		}
		$field='B.p_parent_name,sku,finishTime,protector,cutoff_time,cutoff_money,types';
		$list = $this->fun->getalllist('db_external_buy A left join db_goods_parent B on A.sku = B.p_parent_sku AND B.p_parent_id >0',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		//die;
		
		foreach($list["list"] as $key=>$rs)
		{
			$onefishTime = strtotime($rs["finishTime"])+90*86400;
			$TwofishTime = strtotime($rs["finishTime"])+365*86400;
			$list['list'][$key]["onefinishTime"] = date("Y-m-d H:i:s",$onefishTime);
			$list['list'][$key]["TwofinishTime"] = date("Y-m-d H:i:s",$TwofishTime);
			
			//关于结算时间，如果上次结算时间没有，结算时间为上架时间
			if($rs['cutoff_time'] == '0000-00-00')
			{
				$time1 = $rs["finishTime"];
			}else{
				$time1 = $rs['cutoff_time'];	//如果上次结算了，使用上次结算的时间，已结算的订单不再计算
				//$time1 = $rs["finishTime"];
			}
			
			$money = $this->m->externalBuyrefund_Pro($rs['sku']);
			if(count($money["dates"])>0)
			{
				$money["dates"] = 1;
			}else{
				$money["dates"] = 0;
			}
			$list['list'][$key]["money"] = $money;

			$listcount = $listcount+$money['alllastMoney'];
		}
	
		if($all)
		{
			echo json_encode($listcount);
			die;
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$userlist = $this->fun->getdatabaseslist('db_external_buy'," AND protector is NOT NULL AND del_flag = 0",'DISTINCT(protector)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['protector'];
		}
        $this->tpl->assign("userlist", $yuanl);
		$this -> tpl -> display("datareport/externalBuy_refund.tpl");
	}

	public function scanorder()
	{

		$starttime =$getstarttime= $this->input->post('starttime');	//开始时间
		$endtime   = $this->input->post('endtime');		//结束时间
		$starttime=$starttime==''?date("Y-m-01",strtotime('-1 month')):$starttime;
		$endtime=$endtime==''?date("Y-m-t",strtotime('-1 month')):$endtime;
		//查询开始与结束时间每天的日收入
		$shopname	   = $this->input->post('shopname');
		$shopname=trim($shopname,',');
		
		$can_visit_shop=$this->m->getDsViewShops();
		if($can_visit_shop!='isadmin' && $shopname==''){
			if(!$getstarttime){
				$shopname=$can_visit_shop;
			}
		}

		
		$this->tpl->assign("starttime",$starttime);
		$this->tpl->assign("endtime",$endtime);
		
		$this->tpl->assign("shopname",$shopname);
		$this->tpl->display("datareport/scanorder.tpl");

	}
	public function storereport()
	{

		if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all')	//管理者能看到所有店铺
		{
			$where = "";
		}else{
			
			$shopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
			if($shopname)
			{
				$shopname = unserialize($shopname);
				$where = " (";
				foreach($shopname as $key=>$name)
				{
					if($key>0)
					{
						$or = " or";
					}
					$where.=" $or NAME = '".$name."'";
				}
				$where.=") AND";
			}else{
				die('如果你要查看店铺报表，请先绑定店铺！');//没有绑定的人员不开放权限
			}
		}
		
		$this->load->library('Mabang');
		$res = $this->mabang->getshopname($where);	//获取马帮里面所有的店铺

		
		$this->tpl->assign("shopname",$res);
		$this -> tpl -> display("datareport/storereport.tpl");
	}
	public function searchstore()
	{
		$starttime = $this->input->post('starttime');
		$endtime   = $this->input->post('endtime');
		$shopID	   = $this->input->post('shopID');
		$this->load->library('Mabang');
		$res = $this->mabang->getshopOrder($starttime,$endtime,$shopID);	//获取马帮里面的订单
		$maol = 0;
		$totalst = 0;
		$cb = 0;
		foreach($res as $key=>$rs)
		{
			foreach($rs as $s=>$d)
			{
				$maol =$maol+$d["lastprice"];
				$totalst =$totalst+$d["allmount"];	//总收入
				$cb =$cb+$d["freight"]+$d["Costofgoods"]+$d["PAYPALFEEAMOUNT"]+$d["FINALVALUEFEE"];//总成本

			}
			$newlist[$key]["totalst"] = $totalst;
			$newlist[$key]["cb"] = $cb;
			$newlist[$key]["maolv"] =  round(($totalst-$cb)/$totalst*100,2);
			$newlist[$key]["maol"] = $maol;
		}
		$this->tpl->assign("orderlist",$res);
		$this->tpl->assign("newlist",$newlist);
		$this->tpl->assign("starttime",$starttime);
		$this->tpl->assign("endtime",$endtime);
		$this -> tpl -> display("datareport/searchstore.tpl");
	}
	public function productlist()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$status =  $this->input->get('status');
		if($status){
			$where =" AND status ='".$status."'";
			$this->tpl->assign("status",$status);
		}
		
		$where.=" AND type=0";
		$starttime =trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND opertime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND opertime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = $this->input->get('other');
		if($other)
		{
			$where.=" AND (name like '%".$other."%' or sku like '%".$other."%')";
			$this->tpl->assign("other",$other);
		}

		$id =  $this->input->get('id');
		if($id)
		{
			$where.=" AND id='".$id."'";
		}
		$orderyts =  $this->input->get('ordery');
		if($orderyts)
		{
			$orderby =" order by id {$orderyts}";
			if($orderyts=='ASC')
			{
				$this->tpl->assign("orderyts",'DESC');
			}else{
				$this->tpl->assign("orderyts",'ASC');
			}

		}else{
			$this->tpl->assign("orderyts",'ASC');
		}
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by sku {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$this->tpl->assign("orderbysku",'DESC');
		}
		if(!$orderbysku && !$orderyts)
		{
			$orderby =" order by id desc";
		}
		$list = $this->fun->getalllist('p_product',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			if($rs["status"] ==1)$list["list"][$key]["status"] ="正常";
			if($rs["status"] ==2)$list["list"][$key]["status"] ="清仓";
			if($rs["status"] ==3)$list["list"][$key]["status"] ="下架";
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("datareport/product.tpl");
	}
	
/*
	public function saleproductlist()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$status =  $this->input->get('status');
		if($status){
			$where =" AND status ='".$status."'";
			$this->tpl->assign("status",$status);
		}
		
		$where.=" AND type=1";
		$starttime =trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND opertime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND opertime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = $this->input->get('other');
		if($other)
		{
			$where.=" AND (name like '%".$other."%' or sku like '%".$other."%')";
			$this->tpl->assign("other",$other);
		}

		$id =  $this->input->get('id');
		if($id)
		{
			$where.=" AND id='".$id."'";
		}
		$orderyts =  $this->input->get('ordery');
		if($orderyts)
		{
			$orderby =" order by id {$orderyts}";
			if($orderyts=='ASC')
			{
				$this->tpl->assign("orderyts",'DESC');
			}else{
				$this->tpl->assign("orderyts",'ASC');
			}

		}else{
			$this->tpl->assign("orderyts",'ASC');
		}
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by sku {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$this->tpl->assign("orderbysku",'DESC');
		}
		if(!$orderbysku && !$orderyts)
		{
			$orderby =" order by id desc";
		}
		$list = $this->fun->getalllist('p_product',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			if($rs["status"] ==1)$list["list"][$key]["status"] ="正常";
			if($rs["status"] ==2)$list["list"][$key]["status"] ="清仓";
			if($rs["status"] ==3)$list["list"][$key]["status"] ="下架";
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("datareport/saleproductlist.tpl");
	}
*/

	public function bonus()
	{
		
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		$where =" AND tb =1 AND type=0";
		
		$uname =  $this->input->get('uname');
		if($uname)
		{
			$where.=" AND createUser = '".trim($uname)."'";
			$this->tpl->assign("uname",$uname);
		}

		$starttime =trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND liquidation >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND liquidation <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}

		$rkstartime =trim($this->input->get('rkstartime'));
		if($rkstartime)
		{
			$where.=" AND tbopertime >='".$rkstartime."'";
			$this->tpl->assign("rkstartime",$rkstartime);
		}
		$rkendtime =trim($this->input->get('rkendtime'));
		if($rkendtime)
		{
			$where.=" AND tbopertime <='".$rkendtime."'";
			$this->tpl->assign("rkendtime",$rkendtime);
		}


		$other =trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND ( sku like '%".$other."%' or name like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		$ty =trim($this->input->get('ty'));
		if($ty)
		{
		
			$dates = $ty."-01";
			$startime = date("Y-m-d", strtotime("-7 months", strtotime($dates)));
			$endtime = date('Y-m-t', strtotime($startime));
	
			$where.=" AND tbopertime >='".$startime."' AND tbopertime <= '".$endtime."'";

			$this->tpl->assign("ty",$ty);
		}
		
		$status =trim($this->input->get('status'));
		if($status)
		{
			if($status==1)
			{
				$where.=" AND liquidation <='".date("Y-m-d")."'";
			}else{
				$where.=" AND liquidation >'".date("Y-m-d")."'";
			}
			$this->tpl->assign("status",$status);
		}
		
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by sku {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$this->tpl->assign("orderbysku",'DESC');
		}
		$cr =  $this->input->get('cr');
		if($cr)
		{
			$orderby =" order by createID {$cr}";
			if($cr=='ASC')
			{
				$this->tpl->assign("cr",'DESC');
			}else{
				$this->tpl->assign("cr",'ASC');
			}

		}else{
			$this->tpl->assign("cr",'DESC');
		}

		$allamount = 0;
		$list = $this->fun->getalllist('p_product',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			//$startime= date("Y-m-d", strtotime("+3 months", strtotime($rs["tbopertime"])));
			//$list["list"][$key]["liquidation"] =$startime;
			if($rs["zhixiaotime"])
			{
				$list["list"][$key]["qis"] = date("Y-m", strtotime("+1 months", strtotime($rs["zhixiaotime"])));
			}else{
				$list["list"][$key]["qis"] = "未入库";
			}
			$list["list"][$key]["daysale"] = $this->m->getsalessum(trim($rs["sku"]),2,$rs["tbopertime"]);
			$list["list"][$key]["threedaysale"] = $this->m->getsalessum(trim($rs["sku"]),1,$rs["tbopertime"]);
			$list["list"][$key]["jiudaysale"] = $this->m->getsalessum(trim($rs["sku"]),3,$rs["tbopertime"]);
			
			$rsgoods =$this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".trim($rs["sku"])."'");
			$rsdb = $this->fun->getdatabasesdetail("db_goods_stock"," AND goods_id='".$rsgoods['goods_id']."' and storage_id=1");
			if($rsdb)
				$list["list"][$key]["stocknum"] = $rsdb['stock'];
			else
				$list["list"][$key]["stocknum"] = 0;

			//计算提成金额


			
			$commission = $this->m->commission($rs["tbopertime"],trim($rs["sku"]),$rsgoods["g_costprice"],$rs["activityprice"]);

			$allamount = $allamount+$commission;
			$list["list"][$key]["commissionamount"] = $commission;


			//滞销率	6个月当天的库存/(6个月当天的库存+ 历史销售量)
			if($rs["zhixiaonum"]>0){
				$zhixiaolv =  intval($rs["zhixiaonum"]/($rs["zhixiaonum"]+$rs["xiaoliang"])*100);
				$list["list"][$key]["zhixiaolv"] = $zhixiaolv."%";
				if($zhixiaolv>40)
				{
					//计算死库金额，成本*库存*0.25
					$list["list"][$key]["zhixiaoamount"] = $rsgoods["g_costprice"] * $rs["zhixiaonum"] *25/100;
				}else{
					$list["list"][$key]["zhixiaoamount"] = 0;
				}

			}else{
				$list["list"][$key]["zhixiaolv"] =0;
				$list["list"][$key]["zhixiaoamount"] = 0;
			}

		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		 $this->tpl->assign("allamount", $allamount);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("datareport/bonus.tpl");
	}
	
	/*
	public function salebonus()
	{
		
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		$where =" AND tb =1 AND type=1";
		
		$uname =  $this->input->get('uname');
		if($uname)
		{
			$where.=" AND createUser = '".trim($uname)."'";
			$this->tpl->assign("uname",$uname);
		}

		$starttime =trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND liquidation >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND liquidation <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}

		$rkstartime =trim($this->input->get('rkstartime'));
		if($rkstartime)
		{
			$where.=" AND tbopertime >='".$rkstartime."'";
			$this->tpl->assign("rkstartime",$rkstartime);
		}
		$rkendtime =trim($this->input->get('rkendtime'));
		if($rkendtime)
		{
			$where.=" AND tbopertime <='".$rkendtime."'";
			$this->tpl->assign("rkendtime",$rkendtime);
		}


		$other =trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND ( sku like '%".$other."%' or name like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		$ty =trim($this->input->get('ty'));
		if($ty)
		{
			$year = date("Y",strtotime($ty));
			$month = date("m",strtotime($ty));
			$where.=" AND money_year ='".$year."' AND money_month = '".$month."'";
			$this->tpl->assign("ty",$ty);
		}
		
		$status =trim($this->input->get('status'));
		if($status)
		{
			if($status==1)
			{
				$where.=" AND liquidation <='".date("Y-m-d")."'";
			}else{
				$where.=" AND liquidation >'".date("Y-m-d")."'";
			}
			$this->tpl->assign("status",$status);
		}
		
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by sku {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$this->tpl->assign("orderbysku",'DESC');
		}
		$cr =  $this->input->get('cr');
		if($cr)
		{
			$orderby =" order by createID {$cr}";
			if($cr=='ASC')
			{
				$this->tpl->assign("cr",'DESC');
			}else{
				$this->tpl->assign("cr",'ASC');
			}

		}else{
			$this->tpl->assign("cr",'DESC');
		}

		$allamount = 0;
		$totalsmoney = 0;	//收入金额
		$list = $this->fun->getalllist('p_product',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			//$startime= date("Y-m-d", strtotime("+3 months", strtotime($rs["tbopertime"])));
			//$list["list"][$key]["liquidation"] =$startime;
			if($rs["zhixiaotime"])
			{
				$list["list"][$key]["qis"] = date("Y-m", strtotime("+1 months", strtotime($rs["zhixiaotime"])));
			}else{
				$list["list"][$key]["qis"] = "未入库";
			}
			$list["list"][$key]["daysale"] = $this->m->getsalessum(trim($rs["sku"]),2,$rs["tbopertime"]);
			$list["list"][$key]["threedaysale"] = $this->m->getsalessum(trim($rs["sku"]),1,$rs["tbopertime"]);
			$list["list"][$key]["jiudaysale"] = $this->m->getsalessum(trim($rs["sku"]),3,$rs["tbopertime"]);
			$rsgoods =$this->fun->getdatabasesdetail("db_goods"," AND goods_sku='".trim($rs["sku"])."'");
			$rsdb = $this->fun->getdatabasesdetail("db_goods_stock"," AND goods_id='".$rsgoods['goods_sku']."' and storage_id=1");
			if($rsdb)
				$list["list"][$key]["stocknum"] = $rsdb['stock'];
			else
				$list["list"][$key]["stocknum"] = 0;

			//计算提成金额	提成=0.1*∑（收款金额+运费收入-商品成本-物流成本-平台交易费-付款交易费）
			$commission = $this->m->salecommission($rs["tbopertime"],trim($rs["sku"]),$rs["liquidation"],$rsgoods["g_costprice"]);
			//("amount"=>$amount,"totalsmoney"=>$totalsmoney,"totalexpressask"=>$totalexpressask,"totalcostprice"=>$totalcostprice,"totalcosexpress"=>$totalcosexpress,"totaljiaoyif"=>$totaljiaoyif,"totalfukuanf"=>$totalfukuanf);
			if($commission["totalcosexpress"]==0)
			{
				//echo $rs["sku"];
				//echo "<br>";
			}
			$allamount = $allamount+$commission["amount"];
			$totalsmoney = $totalsmoney+$commission["totalsmoney"];
			$totalexpressask = $totalexpressask+$commission["totalexpressask"];

			$totalcostprice = $totalcostprice+$commission["totalcostprice"];
			$totalcosexpress = $totalcosexpress+$commission["totalcosexpress"];
			$totaljiaoyif = $totaljiaoyif+$commission["totaljiaoyif"];
			$totalfukuanf = $totalfukuanf+$commission["totalfukuanf"];

			$list["list"][$key]["commissionamount"] = $commission["amount"];
			
			//毛利率
			$list["list"][$key]["maolv"] =round($commission["maolvshouru"],2); 

			//滞销率	6个月当天的库存/(6个月当天的库存+ 历史销售量)
			if($rs["zhixiaonum"]>0){
				$zhixiaolv =  intval($rs["zhixiaonum"]/($rs["zhixiaonum"]+$rs["xiaoliang"])*100);
				$list["list"][$key]["zhixiaolv"] = $zhixiaolv."%";
				if($zhixiaolv>40)
				{
					//计算死库金额，成本*库存*0.30
					$list["list"][$key]["zhixiaoamount"] = $rs["costprice"] * $rs["zhixiaonum"] *30/100;
				}else{
					$list["list"][$key]["zhixiaoamount"] = 0;
				}

			}else{
				$list["list"][$key]["zhixiaolv"] =0;
				$list["list"][$key]["zhixiaoamount"] = 0;
			}

		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		 $this->tpl->assign("allamount", $allamount);
		 $this->tpl->assign("totalexpressask", $totalexpressask);
		 $this->tpl->assign("totalcostprice", $totalcostprice);
		 $this->tpl->assign("totalcosexpress", $totalcosexpress);
		 $this->tpl->assign("totalfukuanf", $totalfukuanf);
		  $this->tpl->assign("totaljiaoyif", $totaljiaoyif);
		 $this->tpl->assign("totalsmoney", $totalsmoney);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("datareport/salebonus.tpl");
	}
	*/
	public function orderlist()
	{
	
		
		$sku = $this->input->get('sku');
		$detail = $this->fun->getdatabasesdetail("p_product"," AND sku = '".$sku."'");
		
		$res = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".trim($sku)."'");	//获取马帮里面的数据
		$daysale = $this->m->getsalessum(trim($sku),2,$detail["tbopertime"]);
		$threedaysale = $this->m->getsalessum(trim($sku),1,$detail["tbopertime"]);
		$jiudaysale = $this->m->getsalessum(trim($sku),3,$detail["tbopertime"]);
				//print_r($res);
			//die;
		//查询三个月的清算订单销售//297122641199191964
		
		
		$tbopertime = $detail["tbopertime"];
		$startime1 = date("Y-m-d", strtotime("+3 months", strtotime($tbopertime)));
		$endtime = $startime1." 23:59:59";
		$startime = $tbopertime." 00:00:00";

		$qsorder = $this->m->getsaleslastsum($startime,$endtime,trim($sku));
		$allnums = 0;
		$minvalue = array();
		$Activityprice = 0;
		$amount = 0;
		foreach($qsorder as $key=>$rs)
		{
			$qsorder[$key]['OPERTIMEst'] = $rs['dates'];

			
			$allnums = $allnums+$rs['goods_number'];
			/*
			if($rs->SELLPRICE)
			{
				$fvalue = $rs->SELLPRICE;
				$minvalue[] = $fvalue;
			}*/
		}
		if($detail["activityprice"]>0){
		//$Activityprice = $this->fun->getminarray($minvalue);//活动价即3个月内各平台正常销售的最低价
		$Activityprice =$detail["activityprice"];
		if($allnums>0)
		{
			$amount = $allnums*($Activityprice-$res["g_costprice"])*20/100;
		}
		}



		$this->tpl->assign("res",$res);
		$this->tpl->assign("qsorder",$qsorder);
		$this->tpl->assign("allnums",$allnums);//3个月内的总销售
		$this->tpl->assign("startime",$startime1);
		$this->tpl->assign("daysale",$daysale);
		$this->tpl->assign("Activityprice",$Activityprice);
		$this->tpl->assign("threedaysale",$threedaysale);
		$this->tpl->assign("jiudaysale",$jiudaysale);
		$this->tpl->assign("amount",$amount);
		$this->tpl->assign("detail",$detail);
		$this -> tpl -> display("datareport/orderlist.tpl");
	}
	
	public function saleorderlist()
	{
	
		$sku = $this->input->get('sku');
		$detail = $this->fun->getdatabasesdetail("p_product"," AND sku = '".$sku."'");
		$res = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".trim($sku)."'");	//获取马帮里面的数据

		$stock = $this->fun->getdatabasesdetail("db_goods_stock"," and goods_id='".$res['goods_id']."'  and storage_id=1");	//获取马帮里面的数据
		$daysale = $this->m->getsalessum(trim($sku),2,$detail["tbopertime"]);
		$threedaysale = $this->m->getsalessum(trim($sku),1,$detail["tbopertime"]);

		$jiudaysale = $this->m->getsalessum(trim($sku),3,$detail["tbopertime"]);
			
		
		
		$tbopertime = $detail["tbopertime"];
		$endtime = $detail["liquidation"];
		$startime = $tbopertime;
		
		
			//计算提成金额	提成=0.1*∑（收款金额+运费收入-商品成本-物流成本-平台交易费-付款交易费）
			$commission = $this->m->salecommission($startime,$sku,$endtime,$res["g_costprice"]);
			
		$this->tpl->assign("allnums",$commission["totalsmoney"]);//2个月内的总销售
		$this->tpl->assign("costprice",$commission["totalcostprice"]);
		$this->tpl->assign("totalexpressask",$commission["totalexpressask"]);
		$this->tpl->assign("totalcosexpress",$commission["totalcosexpress"]);
		$this->tpl->assign("totaljiaoyif",$commission["totaljiaoyif"]);
		$this->tpl->assign("totalfukuanf",$commission["totalfukuanf"]);
		
		$this->tpl->assign("startime",$startime1);
		$this->tpl->assign("daysale",$daysale);
		$this->tpl->assign("threedaysale",$threedaysale);
		$this->tpl->assign("jiudaysale",$jiudaysale);
		$this->tpl->assign("amount",$commission["amount"]);
		$endtime = $detail["liquidation"]." 23:59:59";
		$startime = $tbopertime." 00:00:00";
		$qsorder = $this->m->getsaleslastsum($startime,$endtime,trim($sku));
		$allnums = 0;
		$minvalue = array();
		$amount = 0;
		$costprice = 0;
		$sellnumsst = 0;
		$totalexpressask = 0;
	
		foreach($qsorder as $key=>$rs)
		{
			$qsorder[$key]['OPERTIMEst'] =$rs['dates'];
			

			if($rs['shipping_realfee']>0)
			{
				$MONEYEXPRESSASKst = round($rs['shipping_realfee'],2);//真实运费
			}else{
				$MONEYEXPRESSASKst = round($rs['shipping_expectfee'],2);//预估运费
			}
			
			if($MONEYEXPRESSASKst<1)
			{
				//如果没有运费，自动计算10笔运费平均值
				$getyunf = $this->m->getsalembyunf($sku,$startime,$endtime,$rs["country"]);
				$MONEYEXPRESSASKst = $getyunf;	//计算十笔平均值运费
				$qsorder[$key]["yichang"] = 1;
			}else{
				$qsorder[$key]["yichang"] = 0;
			}

			$goodslist = $this->fun->getdatabaseslist("db_order_sell", " AND order_id='" . $rs['order_id'] . "'");
			if(count($goodslist)>1)	//2个以上商品
			{
				$smoney =$rs['goods_amount'];//收款金额
				if($rs["shipping_fee"]>0)
				{
					$expressask = round($rs["shipping_fee"]/count($goodslist),2) ;	//运费收入
				}else{
					$expressask  = 0;
				}
				$cosexpress = round($MONEYEXPRESSASKst/count($goodslist),2) ;	//运费成本
			}else{
				$cosexpress  =$MONEYEXPRESSASKst;//运费成本
			}

			
			$jiaoyif = $rs['platform_fee'];
			$fukuanf =  $rs['pay_fee'];
		
			$qsorder[$key]['MONEYEXPRESSASKst'] =$cosexpress;
			$goods_number = $rs['goods_number'];
			$qsorder[$key]['lvrun'] =round($rs['goods_amount']+$rs['shipping_fee'] - $cosexpress-($res["g_costprice"]*$goods_number)-$jiaoyif-$fukuanf ,2);
			//销售数量
		
			
			$sellnums = $sellnums+$goods_number;
			
		}

		if($this->input->get('csv')==1)
		{
				$filename = $detail["sku"]."-".date('Ymd') . '.csv';
				header("Content-type: text/csv");
				header("content=text/html;charset=utf8");
				header("Content-Disposition: attachment; filename=" . $filename);
				header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
				header('Expires:0');
				header('Pragma:public');
				$str = "订单号,单品销售金额,店铺,订单时间,数量,运费收入,运费成本,利润\r\n";
				  foreach ($qsorder as $v) {
					$str .= "\t" . $v['order_sn'].",".$v['goods_amount']."," . $v['shopname'].",".$v['dates'].",".$v['goods_number'].",".$v['shipping_fee'].",".$v['MONEYEXPRESSASKst'].",".$v['lvrun']."\r\n";
				  }
				  echo mb_convert_encoding($str, "cp936", "UTF-8");
				  exit();
		}
		
	

		$this->tpl->assign("res",$res);
		$this->tpl->assign("qsorder",$qsorder);
		$this->tpl->assign("stock",$stock['stock']);
				
		$this->tpl->assign("sellnums",$sellnums);
		$this->tpl->assign("detail",$detail);
		$this -> tpl -> display("datareport/saleorderlist.tpl");
	}

	public function addproduct()
	{
		$id = $this->input->get('id');
		if($id)
		{
			$where = " AND id='".$id."'";
			$res=$this->fun->getdatabasesdetail('p_product',$where,'*');
		}
		$this->tpl->assign("detail",$res);
		if($this->input->get('type')==1)
		{
		$this -> tpl -> display("datareport/addsaleproduct.tpl");
		}else
		$this -> tpl -> display("datareport/addproduct.tpl");
	}
	public function upfile()
	{
		$arr = $this->fun->newupfile('mypic');
		echo json_encode($arr);
	}
	public function saveproduct()
	{
		if($this->input->post('type')==1)
		{
			$id=$this->m->savesaleproduct();
			header("location:/datareport/saleproductlist?id=".$id);
		}else{
			$id=$this->m->saveproduct();
			header("location:/datareport/productlist?id=".$id);
		}
		
	}
	/*
	public function import($pageid,$num)
	{
		echo "暂时关闭";
		die;
		$nowpage = $pageid;
	    if ($nowpage == "")
			$nowpage = 1;
		else
			$nowpage = $nowpage+1;
	    if ($num == "")$num = 0;
		
		$this->load->library('Mabang');
		$res = $this->mabang->getproductlist($nowpage,$num);

		echo $res;
		echo "<meta http-equiv=\"refresh\" content=\"1; url=/datareport/import/$nowpage/$res\">";
		
	}*/
	/*******************
	***  处理管理系统与内部管理系统之间产品的信息
	***  http://192.168.1.100:89/fshop/
	*** 2017/05/10
	**********/	
		/*
	public function batchproduct()
	{
		if($this->input->get('batch') == 1)
		{
			$pageid = $this->input->get('pageid');
				$nowpage = $pageid;
				if ($nowpage == "")
					$nowpage = 1;
				else
					$nowpage = $nowpage+1;
			$this->load->library('Fshop');
			$res = $this->fshop->batchproductlist($nowpage);
			echo $res."<br>执行完成";
			echo "<meta http-equiv=\"refresh\" content=\"1; url=/datareport/batchproduct?batch=1&pageid=$nowpage\">";
		}elseif($this->input->get('batch') == 2)
		{
			$pageid = $this->input->get('pageid');
				$nowpage = $pageid;
				if ($nowpage == "")
					$nowpage = 1;
				else
					$nowpage = $nowpage+1;
			$this->load->library('Mabang');
			$res = $this->mabang->batchproductimages($nowpage);
			echo $res."<br>执行完成";
			echo "<meta http-equiv=\"refresh\" content=\"1; url=/datareport/batchproduct?batch=2&pageid=$nowpage\">";
		}else{
			$this -> tpl -> display("datareport/batchproduct.tpl");
		}
	}*/
	public function ajaxbutton()
	{
		$op = trim($_REQUEST["op"]);
		if($op =="delimg")
		{
			$file = dirname(__FILE__)."/../../uploads/";
			$filename = $file.$_POST['imagename'];
			
			if(!empty($filename)){
				unlink($filename);
				echo '1';
			}else{
				echo '删除失败.';
			}
			die;
		}
		if($op == 'delproduct')
		{
			$id = $this->m->delproduct();
			echo $id;
			die;
		}
		if($op == 'getsku')
		{
			$sku = $this->input->post('sku');
			if($this->input->post('type'))
			{
				$where = " AND type=1";
			}
			$res = $this->fun->getdatabasesdetail('p_product'," AND sku='".$sku."' $where ");
			if($res)
			{
				echo 201;
				die;
			}
		}
		if($op == 'upmabang')
		{
			$id = $this->input->post('id');
			$rsdb = $this->fun->getdatabasesdetail('p_product'," AND id='".$id."' ");
			$this->load->library('Mabang');
			$res = $this->mabang->getskuname(trim($rsdb["sku"]));
			if($res !=200)
			{
				echo 201;
				die;
			}else{
				//可以更新数据
				$r = $this->mabang->insertdata($id);

				echo $r;
				die;
			}
			
		}

		if($op == 'getexternalBuy')
		{
			
			$this->externalBuy(1);
			echo 1;
			die;
		}
		if($op == 'getnewproductPro')
		{
			
			$this->newproductPro(1);
			echo 1;
			die;
		}
		if($op == 'getjsstockclear')
		{
			
			$this->stockclear(1);
			echo 1;
			die;
		}
		if($op=='savesettlement')
		{
			$haltsalessku = trim($this->input->post('haltsalessku'));
			if($haltsalessku)
			{
			  $shopname = $haltsalessku;
			  $shopnames =substr($shopname,0,-1);
			  $shopnames=explode(',',$shopnames);
			  $whereshop = implode("','",$shopnames);
			  $rsdb = $this->fun->getdatabasesdetail("d_shop"," AND name in('".$whereshop."')","GROUP_CONCAT(id) as id");
			  $shopid = $rsdb['id'];
			  $where.=" AND shopid in($shopid)";
			}

			$list = $this->fun->getdatabaseslist("`db_goods_stock_interest`"," AND isfba = 1 $where");
			$post = "";
			foreach($list as $key=>$rs)
			{
				$interest_allnum = $rs["interest_allnum"] + $rs["interest"];
				$post[$key]["settlement"] = time();
				$post[$key]["interest"] = 0;
				$post[$key]["interest_allnum"] = $interest_allnum;
				$post[$key]["id"] = $rs["id"];
			}

			$this->db->update_batch("`db_goods_stock_interest`",$post,"id");
			
		}
		if($op =='getinterest')
		{
			$other = $this->input->post('other');
			if($this->input->post('shopname'))
			{
				  $shopname = trim($this->input->get_post('shopname'));
				  $shopnames =substr($shopname,0,-1);
				  $shopnames=explode(',',$shopnames);
				  $whereshop = implode("','",$shopnames);
				  $rsdb = $this->fun->getdatabasesdetail("d_shop"," AND name in('".$whereshop."')","GROUP_CONCAT(id) as id");
				  $shopid = $rsdb['id'];
				  $where.=" AND shopid in($shopid)";
			}
			if($this->input->post('other'))
			{
				 $where.=" AND goods_sku like  '%".trim($this->input->post('other'))."%'";
			}
			if($this->input->get_post('int_value'))
			{
				 $where.=" AND interest >='".trim($this->input->post('int_value'))."'";
			}
			$rsdb = $this->fun->getdatabasesdetail('db_goods_stock_interest'," AND isfba = 1 $where","sum(interest) as interest");
			echo $rsdb['interest']?$rsdb['interest']:0;
			die;
		}
		if($op == 'getexternalBuy_refund')
		{
			
			$this->externalBuy_refund(1);
			echo 1;
			die;
		}
		if($op =='saveexternalBuyDate')
		{
			$kaideveloper = $this->input->post('kaideveloper');
			$cutofftime	  = $this->input->post('cutofftime');
			//保存结算人员和时间，需要保存已结算的订单信息
			$this->m->saveexternalBuyDate($cutofftime,$kaideveloper);
			$this->fun->phpalert(2, "结算数据保存成功！","/datareport/externalBuy?starttime=+&endtime=+&other=&developer={$kaideveloper}");
			die;
			die;
		}
		if($op =='savenewProductDate')
		{
			$kaideveloper = $this->input->post('kaideveloper');
			$cutofftime	  = $this->input->post('cutofftime');
			$productid	  = $this->input->post('productid');
		
			//保存结算人员和时间，需要保存已结算的订单信息
			$this->m->savenewProductDate($cutofftime,$kaideveloper,$productid);
			$this->fun->phpalert(2, "结算数据保存成功！","/datareport/newproduct?developer={$kaideveloper}");
			exit;
		}
		if($op =='saveexternalBuyDaterefund')
		{
			$kaideveloper = $this->input->post('kaideveloper');
			$cutofftime	  = $this->input->post('cutofftime');
			//保存结算人员和时间，需要保存已结算的订单信息
			$this->m->saveexternalBuyDaterefund($cutofftime,$kaideveloper);
			$this->fun->phpalert(2, "结算数据保存成功！","/datareport/externalBuy_refund?starttime=+&endtime=+&other=&developer={$kaideveloper}");
			die;
			die;
		}
		if($op =='historyList')
		{
			 $nowpage = $_REQUEST["pageid"];
		  if ($nowpage == "")    $nowpage = 1;
			$where ="";
			if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
			{
				//管理员和财务进来能看到所有人的
				$developer= trim($this->input->get_post('protector'));
				if($developer)
				{

					$where.=" AND protector ='".$developer."'";	//这里使用维护者，后期有可能开发人员和维护人员不是同一个，以维护人员为准
					$this->tpl->assign("developer", $developer);
				}
			}else{
				//其他人只能看到自己
				$where.=" AND protector ='".$_COOKIE["username"]."'";	
				$this->tpl->assign("developer", $_COOKIE["username"]);
			}
		
		$sku = trim($this->input->get('sku'));
		if($sku)
		{
			$where.=" AND (sku ='".$sku."' or order_sn ='".$sku."')";	
			$this->tpl->assign("sku",$sku);
		}

		$starttime = trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND cutoff_time >='".$starttime."'";	
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime = trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND cutoff_time <='".$endtime."'";	
			$this->tpl->assign("endtime",$endtime);
		}
		$eid = trim($this->input->get('eid'));
		if($eid==1 && $sku){
			$baid = $this->m->externalBuyrefund_Pro($sku,1);
			if(count($baid["dates"])>0)
			{
				$baidstr =$baid["dates"];
			}
		}
		
		
		//所有退款信息
		$baidstrlist = "";
		$orderby="GROUP BY sku ORDER BY `isrefund` DESC";
		$listrefund = $this->fun->getdatabaseslist('db_external_report A  ',$where,'sku',$orderby);
		if(count($listrefund)>0)
		{
			foreach($listrefund as $key=>$rs)
			{
				$money = $this->m->externalBuyrefund_Pro($rs["sku"],1);
				if($money["dates"])
				{
					$baidstrlist.=implode(",",$money["dates"]).",";
				}
				$alllastrefundMoney = $alllastrefundMoney+$money["alllastMoney"];
			}
		}


		$orderby = " order by id DESC";
		$if_csv = trim($this->input->get('if_csv'));
		$list = $this->fun->getalllist('db_external_report',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
	
		foreach($list["list"] as $key=>$rs)
		{
			//查询退款订单
			if($baidstrlist){
				$baidstr = trim($baidstrlist,",");
				$baidstr = explode(",",$baidstr);
				if(in_array($rs["id"],$baidstr))
				{
					$list['list'][$key]['isrefundstatus'] = 1;
				}else{
					$list['list'][$key]['isrefundstatus'] = 0;
				}
			}
			
			
			//$list['list'][$key]['add_time'] = date("Y-m-d",$rs['add_time']);
			
		}
		
		//总提成金额
		$allmoney = $this->fun->getdatabasesdetail("db_external_report",$where,"sum(allmoney) as allmoney");
		$lastMoney = $this->fun->getdatabasesdetail("db_external_report",$where,"sum(lastMoney) as lastMoney");
		$wheredb.=$where." AND isrefund = 1";
		$alloverrefundMoney = $this->fun->getdatabasesdetail("db_external_report",$wheredb,"sum(lastMoney) as alloverrefundMoney");	//已结退款数

			

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("alllastrefundMoney",$alllastrefundMoney);//总退款数（已结和未结）
		$this->tpl->assign("allamount",$allmoney["allmoney"]);
		$this->tpl->assign("alllastMoney",$lastMoney["lastMoney"]);//总提成,不包含退款

		 if($if_csv==1){
		        require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
		        $objExcel = new PHPExcel();
		      

		        $objExcel->setActiveSheetIndex(0);
		        $objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
		        $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(22);
		        $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		        $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
		        $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		        $objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(26);
		        $objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
		        $objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
		
		        //设置标题
		        $objExcel->setActiveSheetIndex(0)->setCellValue('A1','商品编号');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('B1','结算日期');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('C1','订单编号');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('D1','发货时间');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('E1','提成金额');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('F1','总利润');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('G1','提成率');
		        $objExcel->setActiveSheetIndex(0)->setCellValue('H1','开发人员');
				$count = 0;
		        foreach($list["list"] as $k=>$v){
			      
			        $count = $k+2;
			        $objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['sku']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['cutoff_time']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['order_sn']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['shipping_time']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['lastMoney']);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['allmoney']);
					if($v['isoff']==0) 
						$isoff = '10%';
					else
						$isoff = '1%';
			        $objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$isoff);
			        $objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$v['protector']);
			     
		        }
		        $excel_name = date("YmdHis");
		        header("Content-type:application/vnd.ms-excel;charset=gb2312");
		        header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
		        header('Cache-Control: max-age=0');
		        $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
		        $objWriter->save('php://output');
		        exit;


	        }

		$this->tpl->assign("alloverrefundMoney",$alloverrefundMoney["alloverrefundMoney"]);
		$nofundMoney = $alllastrefundMoney-$alloverrefundMoney["alloverrefundMoney"];
		$this->tpl->assign("nofundMoney",$nofundMoney);//未结退款数
		$moneyc = $lastMoney["lastMoney"]-$alloverrefundMoney["alloverrefundMoney"];	//所有提成 - 已结退款
		$this->tpl->assign("moneyc",$moneyc);
		$userlist = $this->fun->getdatabaseslist('db_external_buy'," AND protector is NOT NULL",'DISTINCT(protector)');
		foreach($userlist as $key=>$rs)
		{
			$yuanl[] = $rs['protector'];
		}
        $this->tpl->assign("userlist", $yuanl);
		$this -> tpl -> display("datareport/historyList.tpl");


		}
		if($op =='testscanOrder')
		{

			/*
		   $sql = "select `batch_order_sn`,count(*) as count,id from db_mabang_scanorder group by `batch_order_sn` having count>1";
		   $query = $this->db->query($sql);
		    $dates = $query->result_array();
			foreach($dates as $key=>$rs)
			{
				
				$this->db->query("delete from db_mabang_scanorder where id='".$rs["id"]."'");
			}
			echo "OK";
			die;*/




			$res = $this->fun->getdatabaseslist("db_mabang_scanorder","","batch_order_sn,MONEYASK,opertime");
			$i = 1;
			foreach($res as $key=>$rs)
			{
				
				
				$this->load->library('Mabang');
				$resSELL = $this->mabang->getsellprice(trim($rs["batch_order_sn"]),"ORDERNUM,SELLPRICE");
				$sellprice = round($resSELL,2);
				$sellprice = intval($sellprice);
				$MONEYASK  = intval($rs["MONEYASK"]);
				$a = $sellprice - $MONEYASK;
				if(intval($sellprice) != intval($rs["MONEYASK"]))
				{
					
					echo "第{$i}个订单：". $rs["batch_order_sn"]."->".$sellprice."->".$rs["MONEYASK"]."->".$rs["opertime"];
					echo "<br>";
					$i=$i+1;
				}
			}
		}

		if($op =='searchscanorderPro')
		{
		
			/**这个版本替换下面的searchscanorder，searchscanorder暂时不再使用，系统保存一段时间之后可以删除**/
			$starttime =$getstarttime= $this->input->post('starttime');	//开始时间
			$endtime   = $this->input->post('endtime');		//结束时间
			$starttime=$starttime==''?date("Y-m-01",strtotime('-1 month')):$starttime;
			$endtime=$endtime==''?date("Y-m-t",strtotime('-1 month')):$endtime;


			$ordertime = trim($this->input->post('ordertime'));	//订单时间
			if($ordertime)
			{
				$this->tpl->assign("ordertime",$ordertime);
				$ordertime = strtotime($ordertime);
				$endordertime = date("Y-m-t",$ordertime);

				$MorderTime = date("Y-m-d",$ordertime)." 00:00:00";
				$endordertime = $endordertime." 23:59:59";
				
				$ordertimewhere = " and mabangorderTime >='".$MorderTime."' AND mabangorderTime <='".$endordertime."' ";
				
			}

			
			//查询开始与结束时间每天的日收入
			$shopname	   = $this->input->post('shopname');
			$shopname=trim($shopname,',');
			
			$can_visit_shop=$this->m->getDsViewShops();
			if($can_visit_shop!='isadmin' && $shopname==''){
				if(!empty($getstarttime)){
					$shopname=$can_visit_shop;
				}
			}
			
			

			$s = $starttime;
			$e   = $endtime;

			$isform   = $this->input->post('isform');
			if($isform>0)
			{
				$sqlwhere = " AND isform = '".$isform."'";
			}

			 $startime = $starttime . " 00:00:00";
			 $endtime = $endtime . " 23:59:59";
			 $listdb = array();
			 $newlist = array();
			 $allnewmonty =$allnewmontycb=$allnewmontymaol=0;
			$allmount=0;
			$shopname	   = $this->input->post('shopname');
			if (count($shopname) == 0) {
				//die('未选中店铺！');
			}
			if($shopname){
				$shops = explode(",",$shopname);
				$whereshop = implode("','",$shops);
			}
			$listres = $this->db->get_where('db_mabang_scanorder',"SHOPTYPE in('".$whereshop."') AND opertime>='".$s."' AND opertime<='".$e."' $sqlwhere $ordertimewhere AND MONEYACTION =0")->result_array();	//按发货时间计算
			if(count($listres)>0)
			{
				//0成本的进行二次计算
				foreach ($listres as $key => $rs)
				{
					//重新获取订单总成本
					$allmount = $rs["MONEYASK"]+$rs["MONEYEXPRESSASK"];
					$MONEYACTION =  $this->m->getordercosprice($rs["batch_order_sn"]);//获取商品成本
					$lastprice = $rs["maoli"]-$MONEYACTION;
					if($allmount>0)
					$maolilv=round($lastprice/$allmount,2)*100;
					else
					$maolilv = 0;
					
					$this->db->update("db_mabang_scanorder",array("MONEYACTION"=>$MONEYACTION,"maoli"=>$lastprice,"maolilv"=>$maolilv),"id='".$rs['id']."'");
				}
			}
			//重新计算运费
			$listres = $this->db->get_where('db_mabang_scanorder',"SHOPTYPE in('".$whereshop."') AND opertime>='".$s."' AND opertime<='".$e."' $sqlwhere $ordertimewhere AND freight = 0 AND real_freight = 0")->result_array();	//重新计算运费
			if(count($listres)>0)
			{
				
				//0成本的进行二次计算
				foreach ($listres as $key => $rs)
				{
					//重新获取订单总成本
					$freight = $this->fun->get_Estimate_freight($rs["batch_orderweight"],$rs['cn_country'],0,$rs["batch_shipping_name"]);
					if($freight){
						
						
						$allmount = $rs["MONEYASK"]+$rs["MONEYEXPRESSASK"];
						$lastprice = $rs["maoli"]-$freight;
						if($allmount>0)
						$maolilv=round($lastprice/$allmount,2)*100;
						else
						$maolilv = 0;
						$this->db->update("db_mabang_scanorder",array("freight"=>$freight,"maoli"=>$lastprice,"maolilv"=>$maolilv),"id='".$rs['id']."'");
						
					}
				}
			}

			//二次计算真实运费
			$listres = $this->db->get_where('db_mabang_scanorder',"SHOPTYPE in('".$whereshop."') AND opertime>='".$s."' AND opertime<='".$e."' $sqlwhere $ordertimewhere AND real_freight =0 AND isform =2")->result_array();
			if(count($listres)>0)
			{
				foreach ($listres as $key => $rs)
				{
					$rsdb = $this->fun->getdatabasesdetail('db_order_list'," AND order_sn='".$rs["batch_order_sn"]."' ","shipping_realfee");
					if($rsdb['shipping_realfee']>0)
					{
						$freigth = round($rsdb['shipping_realfee'],2);
						
						$allmount = $rs["MONEYASK"]+$rs["MONEYEXPRESSASK"];
						$lastprice = $allmount-$rs["MONEYACTION"] - $rs['FINALVALUEFEE'] - $rs['PAYPALFEEAMOUNT']-$freigth;
						if($allmount>0)
						$maolilv=round($lastprice/$allmount,2)*100;
						else
						$maolilv = 0;
							$this->db->update("db_mabang_scanorder",array("real_freight"=>$rsdb['shipping_realfee'],"maoli"=>$lastprice,"maolilv"=>$maolilv),"id='".$rs['id']."'");
					}
				}
			}
			



			$res = $this->db->get_where('db_mabang_scanorder',"SHOPTYPE in('".$whereshop."') AND opertime>='".$s."' AND opertime<='".$e."' $sqlwhere $ordertimewhere")->result_array();
			 if (count($res) > 0) {
				foreach ($res as $key => $rs){
					$allmount = $rs["MONEYASK"]+$rs["MONEYEXPRESSASK"];
					$rs["allmount"] = $allmount;
					$rs["ORDERID"]  = $rs["batch_order_sn"];
					$rs["CUSTOMERRESERVE2"] = $rs["cn_country"];
					
					if($rs['real_freight']>0)
					{
						$freigth = $rs["real_freight"];
					}else{
						$freigth = round($rs["freight"],2);
					}
					$rs['freigth'] = $freigth;
					$rs["lastprice"] = $rs["maoli"];
					
					$listdb[$rs['SHOPTYPE']][$key] = $rs;
				}
				
				foreach ($listdb as $key => $rs){
					$totalst = $cb=0;
			
					foreach ($rs as $ds => $rsdb){
						$totalst = $totalst+$rsdb["allmount"];
						
						if($rsdb['real_freight']>0)
						{
							$freigth = $rsdb["real_freight"];
						}else{
							$freigth = round($rsdb["freight"],2);
						}
						$shop = $this->db->get_one("SELECT * FROM d_shop WHERE id = '".$rsdb['SHOPTYPEID']."'");
						if($shop['platfrom'] == 1)
						{
							//Ebay
							$cb = $cb+$rsdb["MONEYACTION"]+$freigth+$rsdb["PAYPALFEEAMOUNT"];

						}else{
							$cb = $cb+$rsdb["MONEYACTION"]+$rsdb["PAYPALFEEAMOUNT"]+$rsdb["FINALVALUEFEE"]+$freigth;
						}

					}

					

					$shop = $this->db->get_one("SELECT * FROM d_shop WHERE name= '".$key."'");
					if($shop['platfrom'] ==1){
						$newlist[$key]["platfrom"] = 'Ebay';
					}else{
						$newlist[$key]["platfrom"] = '';
					}

					$shopbill = $this->db->get_one("SELECT insertionFeeRMB,startDate,endDate FROM db_ebay_bill WHERE shopName = '".$key."' and types = 1 and endDate >='".$e."'  AND startDate <='".$s."'");
					
					if($shopbill['insertionFeeRMB'] >0){
						$insertionFeeRMB = $shopbill['insertionFeeRMB'];
						$newlist[$key]["istui"] = 1;
					}else{
						$insertionFeeRMB =0;
						$newlist[$key]["istui"] = 0;
					}
					$newlist[$key]["totalst"] = $totalst;
					$cb = $cb+$insertionFeeRMB;
					$newlist[$key]["cb"] = round($cb,2);
					if($totalst>0){
						$newlist[$key]["maolv"] =  round(($totalst-$cb)/$totalst*100,3);
					}else{
						$newlist[$key]["maolv"] = 0;
					}
					$newlist[$key]["maol"] = round(($totalst-$cb),3);

					$allnewmonty = $allnewmonty+$totalst;	//总收入
					$allnewmontycb = $allnewmontycb+$cb;
					$allnewmontymaol = $allnewmontymaol+$newlist[$key]["maol"];
				}
			 }
			if($allnewmonty>0){
				 $allmallv = round(($allnewmontymaol/$allnewmonty)*100,3);
			}
			
			$this->tpl->assign("allnewmonty",$allnewmonty);
			$this->tpl->assign("allnewmontycb",$allnewmontycb);
			$this->tpl->assign("allnewmontymaol",$allnewmontymaol);
			$this->tpl->assign("allmallv",$allmallv);
			
			$this->tpl->assign("orderlist",$listdb);
			$this->tpl->assign("newlist",$newlist);
			$this->tpl->assign("starttime",$s);
			$this->tpl->assign("endtime",$e);
			
			$this->tpl->assign("shopname",$shopname);

		if($this->input->post('if_csv'))
		{
			$newlistcsv="";
			//需要将数组合并后再导出
			$headers =array("店铺","订单编号","订单收入金额","扫重","国家","物流","运费","商品成本","交易费用","平台使用费","单笔利润","利润率","SKU");
			foreach($listdb as $kc=>$rk)
			{
				foreach($rk as $key=>$rs)
				{
					$newlistcsv[$key]["shopname"] = $kc;
					$newlistcsv[$key]['ORDERID'] = $rs["ORDERID"]; 
					$newlistcsv[$key]["allmount"] = $rs["allmount"]; 
					$newlistcsv[$key]["batch_orderweight"] = $rs["batch_orderweight"];
					$newlistcsv[$key]["CUSTOMERRESERVE2"] = $rs["CUSTOMERRESERVE2"];
					$newlistcsv[$key]["batch_shipping_name"] = $rs["batch_shipping_name"]; 
					$newlistcsv[$key]["freigth"] = $rs["freigth"]; 
					
					$newlistcsv[$key]["MONEYACTION"] = $rs["MONEYACTION"]; 
					$newlistcsv[$key]["PAYPALFEEAMOUNT"] = $rs["PAYPALFEEAMOUNT"]; 
					$newlistcsv[$key]["FINALVALUEFEE"] = $rs["FINALVALUEFEE"]; 
					$newlistcsv[$key]["lastprice"] = $rs["lastprice"]; 
					$newlistcsv[$key]["maolilv"] = $rs["maolilv"]; 
					$newlistcsv[$key]["sku"] = $rs["QLRESERVE2"]; 

				}
			}
			
				if(count($newlistcsv)>0){
					foreach($newlistcsv as $key=>$rs)
					{
						$listdata[$key][] = $rs["shopname"];
						$listdata[$key][] = $rs["ORDERID"]; 
						$listdata[$key][] = $rs["allmount"]; 
						$listdata[$key][] = $rs["batch_orderweight"];
						$listdata[$key][] = $rs["CUSTOMERRESERVE2"];
						$listdata[$key][] = $rs["batch_shipping_name"]; 
						$listdata[$key][] = $rs["freigth"]; 
						$listdata[$key][] = $rs["MONEYACTION"]; 
						$listdata[$key][] = $rs["PAYPALFEEAMOUNT"]; 
						$listdata[$key][] = $rs["FINALVALUEFEE"]; 
						$listdata[$key][] = $rs["lastprice"]; 
						$listdata[$key][] = $rs["maolilv"]."%"; 
						$listdata[$key][] = $rs["sku"]; 
					}
				}
			
			$this->fun->ouputexclePro($headers,$listdata,$starttime."-".$endtime);
		}
			$this -> tpl -> display("datareport/searchscanorder.tpl");
		}



		if($op =='searchscanorder')
		{
			
			/*
					[ORDERID] => 63859138161114600732
					[SHOPTYPE] => Wish-Samcos
					[SHOPTYPEID] => 59
					[MONEYASK] => 132.3		//收款金额
					[MONEYACTION] => 65		//商品成本
					[MONEYEXPRESSASK] => 18.9	//运费收入
					[MONEYEXPRESSACTION] =>		//真实运费
					[SLRESERVE7] => 97.8275		//物流成本
					[PAYPALFEEAMOUNT] =>		//交易费用
					[SELLNUM] => 1			//数量
					[FINALVALUEFEE] => 22.68	//平台交易费
					[QLRESERVE2] => ,17683-GREY-XL,	//sku
					[batch_orderweight] => 609.00		//重量
					[batch_shipping_name] => 中邮小包挂
					[batch_shipping_number] => RH911041751CN
			*/
			$starttime = $this->input->post('starttime');
			$endtime   = $this->input->post('endtime');
			$shopname	   = $this->input->post('shopname');
			
			$this->load->library('Mabang');
			$res = $this->mabang->getsearchscanorder($starttime,$endtime,$shopname);	//获取马帮里面的订单
			$totalst = 0;
			$cb = 0;
			$maol = 0;
			foreach($res as $key=>$rs)
			{
				foreach($rs as $s=>$d)
				{
					//计算预估运费
					if($d["MONEYEXPRESSACTION"])
					{
						$freigth = $d["MONEYEXPRESSACTION"];
					}else{
						$freigth = $this->fun->get_Estimate_freight($d["batch_orderweight"],$d["CUSTOMERRESERVE2"],0,$d["batch_shipping_name"]);
						
					}

					$res[$key][$s]["freigth"] = $freigth;
					if(!is_numeric($freigth))
					{
						$freigth = 0;
					}
					

					$allmount = $d['MONEYASK'] + $d['MONEYEXPRESSASK'];    //商品售价等于商品销售价+运费
					$res[$key][$s]["allmount"] = $allmount;//订单收入金额
					
					if($d["PAYPALFEEAMOUNT"])
					{
						$PAYPALFEEAMOUNT = $d["PAYPALFEEAMOUNT"];
					}else{
						$PAYPALFEEAMOUNT = round($allmount * 0.015,3);	//支付费用
					}

					
					$res[$key][$s]["PAYPALFEEAMOUNT"] = $PAYPALFEEAMOUNT;//订单收入金额
					if(!$d["FINALVALUEFEE"])
					{
						$FINALVALUEFEE = round($allmount * 0.15,3);
					}else{
						$FINALVALUEFEE =$d["FINALVALUEFEE"];
					}
					
					$cb =$cb+$freigth+$d["MONEYACTION"]+$PAYPALFEEAMOUNT+$FINALVALUEFEE;//总成本

					$lastprice = $allmount - $freigth - $d["MONEYACTION"] - $PAYPALFEEAMOUNT - $FINALVALUEFEE;
					$res[$key][$s]["FINALVALUEFEE"] = $FINALVALUEFEE;
					$res[$key][$s]["lastprice"] = round($lastprice,3);
					$res[$key][$s]["allmount"] = $allmount;//订单收入金额
					$totalst =$totalst+$allmount;	//总收入
				}
				$newlist[$key]["totalst"] = $totalst;
				$newlist[$key]["cb"] = $cb;
				$newlist[$key]["maolv"] =  round(($totalst-$cb)/$totalst*100,2);
				$newlist[$key]["maol"] = $totalst-$cb;
			}


		if($this->input->post('if_csv'))
		{
			//需要将数组合并后再导出
			$headers =array("店铺","订单编号","订单收入金额","扫重","国家","物流","运费","商品成本","交易费用","平台使用费","单笔利润");
			foreach($res as $kc=>$rk)
			{
				if(count($rk)>0){
					foreach($rk as $key=>$rs)
					{
						$listdata[$key][] = $kc;
						$listdata[$key][] = $rs["ORDERID"]; 
						$listdata[$key][] = $rs["allmount"]; 
						$listdata[$key][] = $rs["batch_orderweight"];
						$listdata[$key][] = $rs["CUSTOMERRESERVE2"];
						$listdata[$key][] = $rs["batch_shipping_name"]; 
						$listdata[$key][] = $rs["freigth"]; 
						$listdata[$key][] = $rs["MONEYACTION"]; 
						$listdata[$key][] = $rs["PAYPALFEEAMOUNT"]; 
						$listdata[$key][] = $rs["FINALVALUEFEE"]; 
						$listdata[$key][] = $rs["lastprice"]; 
					}
				}
			}
			$this->fun->ouputexclePro($headers,$listdata,$starttime."-".$endtime);
		}
			
			$this->tpl->assign("orderlist",$res);
			$this->tpl->assign("newlist",$newlist);
			$this->tpl->assign("starttime",$starttime);
			$this->tpl->assign("endtime",$endtime);
			$this->tpl->assign("shopname",$shopname);

			
			$this -> tpl -> display("datareport/searchscanorder.tpl");
		}
		
		/**每天定时读取马帮的发货订单，存入新系统**/
		if($op =='getallscanorder')
		{
			$this->load->library('Mabang');
			$res = $this->mabang->getallscanorder();	//获取马帮里面的订单
		}
		if($op =='getallscanorderPro')
		{
			$this->load->library('Mabang');
			$res = $this->mabang->getallscanorderPro();	//获取马帮里面的订单
		}
		
		/**每天定时读取新系统的发货订单，存入系统**/
		if($op =='getallnewscanorder')
		{
			$res = $this->m->getallscanorder();	//获取新系统订单
		}

		if($op =='getmabangproduct')	//获取马帮的SKU数量
		{
			$sku =trim($this->input->post('sku'));
			$this->load->library('Mabang');
			$res = $this->mabang->getskuname($sku);
			if($res==200)
			{
				echo 201;
				die;
			}else{
				$goods = $this->mabang->updatelocalhostproduct($sku);
				if($goods["tbopertime"])	//入库时间
				{
					//清算时间
					//$liquidation = date("Y-m-d", strtotime("+2 months", strtotime($goods["tbopertime"])));
					//$season = ceil((date('n',$goods["tbopertime"]))/3);//当月是第几季度
					//$liquidation = date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')));
					//echo "<xmp>";
					$res[0]->tbopertime = $goods["tbopertime"];
					//$res[0]->liquidation = $liquidation;
				}
			
				echo json_encode($res);
				die;
			}
			
		}
		if($op =='savehaltsales')
		{
		
		
			$haltsalessku =trim($this->input->post('haltsalessku'),",");
			if($haltsalessku)
			{
				$haltsalessku_list = explode(",",$haltsalessku);
				
				foreach($haltsalessku_list as $key=>$parentID)
				{
					 $parentID = intval($parentID);	//父SKU

					 $goodslist = $this->fun->getdatabaseslist('db_goods'," AND goods_parentID IN($parentID)","goods_id,goods_parentID,goods_name,goods_parent_sku,goods_sku");
					 if(count($goodslist)>0)
					 {
						foreach($goodslist as $key=>$rsdb){
							$goods_id = $rsdb["goods_id"];
							$stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND goods_id IN ($goods_id) AND B.is_show = 1"," SUM(stock) as stock,positions,storage_name");
							

							$rsclear = $this->fun->getdatabasesdetail('db_goods_clear_list'," AND goods_id='".$goods_id."'");
							if(!$rsclear){
								$post="";
								$post["parent_id"] = $rsdb["goods_parentID"];
								$post["goods_id"] = $goods_id;
								$post["goods_sku"] = $rsdb["goods_sku"];
								$post["goods_name"] = $rsdb['goods_name'];
								$post["positions"] = $stock['positions'];
								$post["storage_name"] = $stock['storage_name'];
								$post["stock"] = $stock['stock'];
								$post["types"] = 1;
								$post["oper"] = $_COOKIE['username'];
								$post["uptime"] = time();
								$this->db->insert("db_goods_clear_list",$post);
							}else{
								$post="";
								$post["parent_id"] = $rsdb["goods_parentID"];
								$post["goods_id"] = $goods_id;
								$post["goods_sku"] = $rsdb["goods_sku"];
								$post["goods_name"] = $rsdb['goods_name'];
								$post["positions"] = $stock['positions'];
								$post["storage_name"] = $stock['storage_name'];
								$post["stock"] = $stock['stock'];
								$post["types"] = 1;
								$post["oper"] = $_COOKIE['username'];
								$this->db->update("db_goods_clear_list",$post," id='".$rsclear['id']."'");
							}
					 
						}
			
					 }
					 /*
					 print_r($goodslist);
					 die;
					 $stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND goods_id IN ($goods_id) AND B.is_show = 1"," SUM(stock) as stock,positions,storage_name");
					 if($stock["stock"]>0)
					 {
						//如果有库存，进入待清仓处理
						$rsclear = $this->fun->getdatabasesdetail('db_goods_clear_list'," AND goods_id='".$goods_id."'");
						if(!$rsclear){
							$post="";
							$post["goods_id"] = $goods_id;
							$post["goods_sku"] = $rsdb["goods_sku"];
							$post["goods_name"] = $rsdb['goods_name'];
							$post["positions"] = $stock['positions'];
							$post["storage_name"] = $stock['storage_name'];
							$post["stock"] = $stock['stock'];
							$post["oper"] = $_COOKIE['username'];
							$post["uptime"] = time();
							$this->db->insert("db_goods_clear_list",$post);
						}
					 
					 }else{
						//设置停售，
						$res = $this->db->get_where('db_goods',"goods_parent_sku='".$rsdb["goods_parent_sku"]."'")->result_array();
						if(count($res)==1)
						{
							//如果为一，则父目录商品也标删除
							 $this->db->update('db_goods_parent',array("p_yz"=>2,"p_sale_status"=>4), 'p_parent_id=' . $rsdb["goods_parentID"]);
						}
						 $this->db->update('db_goods',array("yz"=>2,"g_sale_status"=>4), 'goods_id=' . $goods_id);
						 $this->fun->insertsysstatistical('status',4,$goods_id,0);
					 }
					*/
				}
			}
			 $this->fun->phpalert(4, "", '', "/datareport/haltsales");
            die;
		}

		if($op =='savehaltsalescheck')
		{
			$haltsalessku =trim($this->input->post('haltsalessku'),",");
			if($haltsalessku)
			{
				$haltsalessku_list = explode(",",$haltsalessku);
				
				
				foreach($haltsalessku_list as $key=>$id)
				{
					$up = 1;
					$rsclear = $this->fun->getdatabasesdetail('db_goods_clear_list'," AND id='".$id."'");	
					
					$res = $this->db->get_where('db_goods_clear_list',"parent_id='".$rsclear["parent_id"]."'")->result_array();
					foreach($res as $key=>$rs)
					{
						$stock = $this->fun->getdatabasesdetail("db_goods_stock A left join db_storage B on A.storage_id = B.id "," AND goods_id IN ($rs[goods_id]) AND B.is_show = 1"," SUM(stock) as stock,positions,storage_name");
						if($stock["stock"]>0)
						{
							 //如果1、2号仓为0 说明是海外仓有库存，直接标清仓
							 $questock = $this->fun->getdatabasesdetail("db_goods_stock"," AND goods_id IN ($rs[goods_id]) AND storage_id in(1,2) "," SUM(stock) as stock");
							 if($questock['stock'] ==0)
							 {
								$up = 2;
								$this->fun->goods_update_log($rs['goods_id'], '海外仓有库存修改成清仓状态', 1);    //更新商品信息
								$this->fun->insertsysstatistical('status',5,$rs['goods_id'],0);	//设置停售
								$this->db->update('db_goods',array("yz"=>0,"g_sale_status"=>5), 'goods_id=' . $rs['goods_id']);//SKU清仓
								$this->db->delete('db_goods_clear_list', 'goods_id=' . $rs['goods_id']);//删除
							 }else{
								 $up = 0;
								 $this->db->update('db_goods_clear_list',array("types"=>0), 'goods_id=' . $rs['goods_id']);//进入待清仓流程
							 }
							
						}else{
							 //标日志
						    $this->fun->goods_update_log($rs['goods_id'], '修改成停售状态', 1);    //更新商品信息
							$this->fun->insertsysstatistical('status',4,$rs['goods_id'],0);	//设置停售
							//
							$this->db->update('db_goods',array("yz"=>2,"g_sale_status"=>4), 'goods_id=' . $rs['goods_id']);//SKU停售
							$this->db->delete('db_goods_clear_list', 'goods_id=' . $rs['goods_id']);//删除
						}
					}
					if($up==1)
					{
						$this->db->update('db_goods_parent',array("p_yz"=>2,"p_sale_status"=>4), 'p_parent_id=' . $rsclear["parent_id"]);//父目录停售
					}
					if($up==2)
					{
						$this->db->update('db_goods_parent',array("p_yz"=>0,"p_sale_status"=>5), 'p_parent_id=' . $rsclear["parent_id"]);//父目录停售
					}
				}
			}
			 $this->fun->phpalert(4, "", '', "/datareport/haltsales_check");
            die;
		}
		if($op =='nocheckhalt')
		{
			$goods_idstr = trim($this->input->post('goods_idstr'),',');
			if($goods_idstr)
			{
				$goods_id = explode(",",$goods_idstr);
				foreach($goods_id as $key=>$rs)
				{
					$rsclear = $this->fun->getdatabasesdetail('db_goods_clear_list'," AND id='".$rs."'");
					$this->db->update('db_goods_clear_list',array("types"=>2), 'parent_id=' . $rsclear['parent_id']);//SKU停售
				}
			}
			echo 200;
			die;
		}

		
		if($op =='setgoods_recommend')
		{
			$parentid = $this->input->post('parentid');
			$parentsku = $this->input->post('parentsku');

			$post ="";
			$post["parent_sku"] = trim($parentsku);
			$post["is_stop"]	= 1;
			$post["parent_goods_id"]	= intval($parentid);
			$this->db->insert('db_goods_recommend',$post);
			echo 200;
			die;
		}



		if($op=="doRecommendGoods"){
            $str_ids = trim($this->input->post("ids"),","); //商品编号id
            //$str_receivers = trim($this->input->post("receiver"),","); //用户id
            $receivers = trim($this->input->post("receiver"),","); //用户id
            $arr_receivers = explode(",",$receivers);
            $arr_ids = explode(",",$str_ids);
			
			

            foreach($arr_ids as $k=>$v){
                $str_receivers = "";
                $sql = "SELECT * FROM db_goods_recommend WHERE is_stop = 0 AND  parent_goods_id= {$v} ";
                $rs  = $this->db->query($sql)->row_array();
                if(count($rs)>0){
                    if($rs['receivers']){
                        $flag = 0;
                        $receiver = trim($rs['receivers'],",");
                        $arr_receiver = explode(",",$receiver); //数据库中已存在用户
                        //新推荐用户 要过滤重复用户
                        $arr_new = array();
                        foreach($arr_receivers as $key=>$value){
                            if(in_array($value,$arr_receiver)){
                                continue;
                            }else{
                                $arr_new[] = $value;
                            }
                        }
                        if(count($arr_new)>0){
                            $str_receivers = $rs['receivers'].implode(",",$arr_new).",";
                            $flag = 1;
                        }
                    }else{
                        $str_receivers = ",".$receivers.",";
                        $flag = 1;
                    }
                    if($flag ==1){
                        $this->db->update('db_goods_recommend',array('receivers'=>$str_receivers),"  parent_goods_id = {$v} ");
                    }
                }else{
					$post ="";
					$res = $this->fun->getdatabasesdetail("db_goods_parent"," AND p_parent_id = '".$v."'",'p_parent_sku,p_parent_name');
					$str_receivers = ",".$receivers.",";
					$post["parent_sku"] = trim($res['p_parent_sku']);
					$post["is_stop"]	= 0;
					$post["goods_name"]	= $res["p_parent_name"];
					$post["recommend"]	= $_COOKIE["username"];
					$post["receivers"]  = $str_receivers;
					$post["parent_goods_id"]	= intval($v);
					$this->db->insert('db_goods_recommend',$post);                

                }
            }
            echo 200;exit; //推荐成功
        }
		//已完成
		if($op == "doFinish"){
			$goods_parent_sku = trim($this->input->post("goods_parent_sku"));
			$linkUrl = trim($this->input->post("linkUrl"));
			$this->db->update("db_goods_recommend",array("status"=>1,"linkUrl"=>$linkUrl)," parent_sku = '".$goods_parent_sku."'");
			echo 200;exit;
		}
		/**********顺丰保存马帮订单信息***/
		if($op=="savemabangorder")
		{
			$orderlist = $this->input->post('orderlist');
            if ($orderlist==""){
                $this->fun->phpalert(2, "马帮订单号必须填写！");
				die;
            }
			$this->load->library('Mabang');
			$res= $this->mabang->savemabangorderlist($orderlist);
            if($res==200)
			{
				$postdata["isexe"] = 0;
				$postdata["exetype"] = 1;	//顺丰交运
				$postdata["comment"] = "/doit/sfexpress";
				$res = $this->db->query($this->db->insert_string('db_crontab', $postdata));
				$this->fun->phpalert(2, "保存成功！请点击列表上面的批量交运顺丰");
				die;
			}
		 
		}
		/**********同步马帮订单信息***/
		if($op=="dodistribution")
		{
			$id = $this->input->post('str');
			$id = substr($id,0,-1);
			$inid = explode(",",$id);
			
			foreach($inid as $key=>$order)
			{
				$rsdb = $this->fun->getdatabasesdetail('db_mabangorder'," AND id='".$order."'");
				$rsdborder = $this->fun->getdatabasesdetail('db_order_list'," AND order_sn='".$rsdb['orderID']."'");

				if($rsdborder["order_status"] ==2){
					$postdata["statusst"] = '配货中';
					$this->db->query($this->db->update_string('db_mabangorder', $postdata, "orderID='".$rsdb["orderID"]."'"));

					if($rsdb["isform"]==1){
						$this->load->library('Mabang');
						$this->mabang->updateordersfexpress($rsdb["orderID"],$rsdb["mailNo"],'顺丰速运',13);
					}else{
						$update_order="";
						$update_order['order_status'] = 3; //状态位配货中
						/*	
						$update_order["shipping_number"] = $rsdb["mailNo"];	//运单号
						$update_order["shipping_time"] = time();				//交运时间
						$update_order["shipping_name"] = "顺丰速运";
						$shipping =$this->fun->getdatabasesdetail("db_order_express"," AND name='".$update_order["shipping_name"]."'");
						$update_order["shipping_id"] = $shipping["id"];*/
						$this->db->query($this->db->update_string('db_order_list', $update_order, "order_sn='".$rsdb["orderID"]."'"));


						//更新日志记录
						$sql = "SELECT * FROM db_order_list WHERE order_sn = '{$rsdb["orderID"]}' ";
						$rs = $this->db->query($sql)->row_array();
						if(count($rs)>0){
							$imgdata["goods_id"] = $rs['order_id'];	//订单ID db_order_list
							$imgdata["updatetime"] = date("Y-m-d H:i:s");
							$imgdata["createUid"] = $_COOKIE['userid'];
							$imgdata["types"] = 3;
							$imgdata["content"] = '修改状态为：配货中';
							$imgdata["createUser"] =$_COOKIE['username'];
							$this->db->insert('db_goods_log', $imgdata);
						}
					}
				}else{
					$postdata="";
					if($rsdborder["order_status"] ==1)
					{
						$postdata["statusst"] = '新订单状态';
					}
					if($rsdborder["order_status"] ==3)
					{
						$postdata["statusst"] = '当前是配货中状态';
					}
					if($rsdborder["order_status"] ==4)
					{
						$postdata["statusst"] = '当前已发货状态';
					}
					if($rsdborder["order_status"] ==5)
					{
						$postdata["statusst"] = '当前已完成状态';
					}
					if($rsdborder["order_status"] ==6)
					{
						$postdata["statusst"] = '当前已作废状态';
					}
					
					$this->db->query($this->db->update_string('db_mabangorder', $postdata, "orderID='".$rsdb["orderID"]."'"));
				}
			}

			echo 200;
			die;

		}

		//查看详细报表
		if($op == "newproductList"){
			$sku = trim($this->input->get('sku'));
			$sql_develop = "SELECT * FROM db_product_develop WHERE sku = '{$sku}' ";
			$rs_develop  = $this->db->query($sql_develop)->row_array();
			$where = " WHERE 1 ";
			$where.= " AND b.dates>= '{$rs_develop['startdate']}' AND b.dates <= '{$rs_develop['enddate']}' ";
			if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
			{
				//管理员和财务进来能看到所有人的

			}else{
				//其他人只能看到自己
				//$where=" AND A.protector ='".$_COOKIE["username"]."'";
			}
			$where .= " AND a.goods_id in (SELECT goods_id FROM db_goods WHERE goods_parent_sku = '{$sku}') ";

			//亚马逊平台存在的订单
			$where_amazon = $where." GROUP BY a.ordertmpid ";
			$fields_amazon = "a.ordertmpid as order_id,b.tradeid as order_sn,b.goods_amount,b.shipping_fee,b.pay_fee";
			$fields_amazon.= ",b.platform_fee,b.shopname ";
			$sql_amazon = "SELECT {$fields_amazon} FROM db_amzordertmpsell a LEFT JOIN db_amzordertmp b ON a.ordertmpid = b.id ".$where_amazon;
			$rs_amazon  = $this->db->query($sql_amazon)->result_array();
			$this->tpl->assign("listamazon",$rs_amazon);

			$where .= " AND b.order_status in(4,5) AND b.order_source in('正常订单','手工创建','拆分订单','合并订单') ";
			$where .= " GROUP BY a.order_id ";
			$fields = "a.order_id,b.order_sn,b.order_source,b.goods_amount,b.shipping_fee,b.pay_fee,b.platform_fee,b.shopname,b.shipping_realfee,b.shipping_expectfee,b.shipping_time";
			$sql = "SELECT {$fields} FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id ".$where;
			$rs  = $this->db->query($sql)->result_array();
			$total_money = 0;
			$total_costprice = 0;
			$total_profit = 0;
			foreach($rs as $k=>$v){
				$sql_costprice = "SELECT SUM(costprice) as costprice FROM db_order_sell WHERE order_id = '{$v['order_id']}' ";
				$rs_costprice  = $this->db->query($sql_costprice)->row_array();
				$rs[$k]['costprice'] = $rs_costprice['costprice'];
				$rs[$k]['profit'] = $v['goods_amount']+$v['shipping_fee']-$rs_costprice['costprice']-$v['platform_fee']-$v['pay_fee']-$v['shipping_realfee'];
				$total_money+=$v['goods_amount'];
				$total_costprice+=$rs_costprice['costprice'];
				$total_profit+=$rs[$k]['profit'];
				if($v['shipping_time']){
					$rs[$k]['shipping_time'] = date("Y-m-d H:i:s",$v['shipping_time']);
				}else{
					$rs[$k]['shipping_time'] = "";
				}

			}
			$this->tpl->assign("total_money",$total_money);
			$this->tpl->assign("total_costprice",$total_costprice);
			$this->tpl->assign("total_profit",$total_profit);
			$this->tpl->assign("list",$rs);
			$this -> tpl -> display("datareport/newproductlist.tpl");


		}


	}
}
